【发布时间】:2020-08-21 22:56:04
【问题描述】:
我正在学习 JavaScript 的原型链和for...in,想知道是否可以覆盖一些内置方法的数据属性。我有以下sn-p:
function Parent(name) {
this.name = name;
}
Parent.prototype.sex = "Male";
function Child(name, age) {
Parent.call(this, name);
this.age = age;
}
Child.prototype = Object.create(Parent.prototype);
Object.defineProperty(Child.prototype, "constructor", {
value: Child,
enumerable: false,
});
const person1 = new Child("John", 26);
for (const key in person1) {
console.log(key);
}
// name
// age
// sex
上面基本上是设置一个简单的继承,底部的for...in迭代按预期工作。最重要的是,它能够在原型链的上层找到sex 属性。
我假设所有这些对象在它们的原型链中都有Object.prototype,但我没有从Object.prototype 对象的for...in 循环中记录任何键的原因是因为它们都有@ 987654328@ 数据属性集。所以我试图覆盖配置:
const fromEntries = Object.fromEntries; // a random non-enumerable method
Object.defineProperty(Object, "fromEntries", {
value: fromEntries,
enumerable: true,
});
console.log(Object.getOwnPropertyDescriptor(Object, 'fromEntries'));
// { value: [Function: fromEntries], writable: true, enumerable: true, configurable: true }
for (const key in person1) {
console.log(key);
}
// name
// age
// sex
问题是,我仍然没有将“fromEntries”方法登录到我的for...in 循环中。我是否对原型链的工作方式做出了错误的假设?还是因为Object.prototype 是不可配置的或类似的?任何帮助表示赞赏!
【问题讨论】:
-
您在 Object 上更改它,该类(与 Object.prototype 相对)不在 person1 的继承链中。对象 instances 没有内置的 fromEntries 方法。
标签: javascript prototype