对象继承和构造函数继承

对象继承

指定哪个对象是新对象的[[prototype]]

对象字面量隐式指定Object.prototype为其[[prototype]]:

var person = {
    name: 'u14e'
};
// 等同于
var person = Object.create(Object.prototype, {
    name: {
        configurable: true,
        enumerable: true,
        value: 'u14e',
        writable: true,
    }
});
var person1 = {
    name: 'u14e',
    sayName: function() {
        alert(this.name);
    }
};
var person2 = Object.create(person1, {
    name: {
        configurable: true,
        enumerable: true,
        value: 'u148',
        writable: true,
    }
});

person1.hasOwnProperty('sayName');      // true
person1.isPrototypeOf(person2);         // true
person2.hasOwnProperty('sayName');      // false

构造函数继承

创建一个函数时,函数自动生成一个prototype属性,这个属性被自动设置为一个新的继承自Object.prototype的原型对象

function Foo() {}
// js引擎背后设置prototype
Foo.prototype = Object.create(Object.prototype, {
    constructor: {
        configurable: true,
        enumerable: true,
        value: Foo,
        writable: true,
    }
})
function Rectangle(length, width) {
    this.length = length;
    this.width = width;
}
Rectangle.prototype.getArea = function() {
    return this.length * this.width;
};

function Square(size) {
    Rectangle.call(this, size, size);
}
Square.prototype = Object.create(Rectangle.prototype, {
    constructor: {
        configurable: true,
        enumerable: true,
        value: Square,
        writable: true,
    }
});

你可能感兴趣的:(对象继承和构造函数继承)