谁能给我解释一下这里到底发生了什么?
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()); //returns 20.99
最佳答案
这是由于 prototype-chain 的后果而发生的.声明
var customObject = Object.create(myObject);
创建一个对象,其原型(prototype)设置为 myObject
。现在您正在分配和删除其上的属性 price
。但它不会改变其原型(prototype)中已有的内容。
您可以尝试在删除属性 price
之前将 customObject
打印到控制台。您将看到该对象包含一个属性 price
,其值设置为 19.99,但其 __proto__
属性的 price
仍为 20.99。运行以下代码片段,并观察浏览器控制台中的输出。
var myObject = {
price: 20.99,
get_price: function() {
return this.price;
}
};
var customObject = Object.create(myObject);
customObject.price = 19.99;
console.log(customObject);
函数get_price
返回this.price
,它在当前对象中搜索一个属性price
,如果没有找到,则递归遍历此属性的原型(prototype)链。由于此属性存在于对象的直接原型(prototype)中,因此返回值 20.99。
关于Javascript 分配和删除属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51997626/