# 原型链

function SuperType() {
    this.property = true;
}

SuperType.prototype.getSuperValue = function() {
    return this.property;
};


function SubType() {
    this.subproperty = false;
}

// SuperType的实例,继承了SuperType
SubType.prototype = new SuperType();

SubType.prototype.getSubValue = function() {
    return this.subproperty;
};

// 继承了SubType
var instance = new SubType();

instance.getSuperValue();
// true
  • SubType继承了SuperType的属性和方法
SubType.prototype;

// SuperType {property: true, getSubValue: ƒ}
//     getSubValue: ƒ ()
//     property: true
//     __proto__:
//         getSuperValue: ƒ ()
//         constructor: ƒ SuperType()
//         __proto__: Object

  • property在SubType.prototype里
SuperType.prototype;

    // {getSuperValue: ƒ, constructor: ƒ}
    //     getSuperValue: ƒ ()
    //     constructor: ƒ SuperType()
    //     __proto__: Object
  • instance.constructor 指向SuperType
instance;

    // SubType {subproperty: false}
    // subproperty: false
    // __proto__: SuperType
    //     getSubValue: ƒ ()
    //     property: true
    //     __proto__: Object

instance.constructor;

// ƒ SuperType() {
//     this.property = true;
// }

image

  • 完整的原型链,包含Object

image

  • 使用instanceof方法确定实例和原型之间的关系
instance instanceof Object;
// true

instance instanceof SubType;
// true

instance instanceof SuperType;
// true
  • 使用Object.prototype.isPrototypeOf()确定实例和原型之间的关系
Object.prototype.isPrototypeOf(instance);
// true

SuperType.prototype.isPrototypeOf(instance);
// true

SubType.prototype.isPrototypeOf(instance);
// true
  • 使用对象字面量定义会切断原型链,使继承无效
function SuperType() {
    this.property = true;
}

SuperType.prototype.getSuperValue = function() {
    return this.property;
};

function SubType() {
    this.subproperty = false;
}

SubType.prototype = new SuperType();

// 使上面的继承无效
SubType.prototype = {
    getSubValue: function() {
        return this.subproperty;
    },
    someOtherMethod: function() {
        return false;;
    }
};

var instance = new SubType();

instance.getSuperValue();
// VM13422:1 Uncaught TypeError: instance.getSuperValue is not a function

  • 原型链的问题:引用类型的共享
function SuperType() {
    this.colors = ["red", "blue", "green"];
}

function SubType() {
}

SubType.prototype = new SuperType();

var instance1 = new SubType();

instance1.colors.push("black");

instance1.colors;
// ["red", "blue", "green", "black"]

var instance2 = new SubType();

instance2.colors;
// ["red", "blue", "green", "black"]
Last Updated: 6/13/2020, 10:22:44 PM