Javascript 中的所有对象都有一个__proto__ 属性,称为它的原型。 (它与某些函数上的prototype 属性不同,原因我不会讨论。)
原型链是在请求时查找某个名称的顺序。例如dog.bark 将在dog 中搜索'bark',但如果dog 没有'bark' 属性,它将在dog.__proto__ 中搜索'bark',依此类推,直到到达原型链。
使用方括号语法 ({}) 声明的新对象将 Object 作为其原型。
函数Object.create(some) 返回一个以some 为原型的新对象。 (some 可以是null 来创建没有原型的对象)。
var myObject = {
price: 20.99,
get_price: function() {
return this.price;
}
};
var customObject = Object.create(myObject);
customObject.price = 19.99; // *
delete customObject.price; // **
console.log(customObject.get_price());
在 * 中,对象 customObject 如下所示:
customObject = {
price: 19.99,
__proto__: {
price: 29.99,
get_price: function() { return this.price; }
}
};
在 ** 中,对象 customObject 如下所示:
customObject = {
__proto__: {
price: 29.99,
get_price: function() { return this.price; }
}
};
delete operator只删除自己的属性,这意味着那些属性直接属于对象(而不是其原型)。
因此,我们删除了price: 19.99,现在我们在尝试获取customObject.price 时得到price: 29.99(这是get_price 所做的)。
如果我们调用myObject.get_price(),我们得到myObject.price,而在customObject.get_price(),我们得到customObject.price。虽然get_price函数实际上在customObject.__proto__内部,但函数调用中的特殊变量this指的是调用函数的对象,而不是函数所属的对象。
如果您认为同一个函数可以属于不同的对象,这是有道理的。