js继承面试速记(内容抄自高程三)

390 阅读1分钟
  • 原型链

    function SuperType(){
        this.property = true;
    }
    SuperType.prototype.getSuperValue = function(){
        return this.property;
    }
    function SubType(){
        this.subproperty = false;
    }
    // 通过将原型指向另一个类型的事例来继承
    SubType.prototype = new SuperType();
  • 借用构造函数
  • function SuperType(){
        this.colors = ['red','blue','green'];
    }
    function SubType(){
        // 继承了SuperType
        SuperType.call(this)
    }

  • 组合继承(伪经典继承)
  • function SuperType(name){
        this.name = name;
        this.colors = ['red','blue','green']
    }
    SuperType.prototype.sayName = function(){
        alert(this.name)
    }
    function SubType(name,age){
        // 继承属性
        SuperType.call(this,name)
        this.age = age;
    }
    // 继承方法
    SubType.prototype = new SuperType();
    SubType.prototype.constructor = SubType;
    
    

  • 原型式继承
  • function object(o){
        function F(){}
        F.prototype = o;
        return new F();
    }
    var person = {
        name:"Nicholas",
        friends:["Shelby","Court","Van"]
    };
    // 实现继承
    var anotherPerson = object(person);

  • 寄生式继承
  • function createAnother(original){
        var clone = object(original)  //原型式继承中的object方法
        clone.sayHi = function(){
            alert('hi')
        };
        return clone;
    }
    var person = {
        name:'Nicholas',
        friends:['Shelby','Court','Van']
    }
    // 实现继承
    var anotherPerson = createAnother(person)

  • 寄生组合式继承
  • function inheriPrototype(subType,superType){
        var prototype = object(supeType.prototype);   // 继承方法
        prototype.constructor = subType;
        subType.prototype = prototype;
    }
    function SuperType(name){
        this.name = name;
        this.colors = ['red','blue','green'];
    }
    superType.prototype.sayName = function(){
        alert(this.name);
    }
    function SubType(name,obj){
        // 继承属性
        SuperType.call(this,name);
        this.age = age;
    }
    // 继承方法
    inheritPrototype(SubType,SuperType)