如何解决JavaScript覆盖对象属性的可枚举性仍然无法枚举
我正在学习JavaScript的原型链和for...in
,并且想知道是否有可能覆盖内置方法的某些data属性。我有以下代码段:
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
,但是我在for...in
对象的Object.prototype
循环中没有登录任何键的原因是因为它们都设置了enumerable: false
数据属性。所以我试图覆盖配置:
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,configurable: true }
for (const key in person1) {
console.log(key);
}
// name
// age
// sex
问题是,我的for...in
循环中仍然没有'fromEntries'方法登录。我是否对原型链的工作方式做出错误的假设?还是因为Object.prototype
是不可配置的或类似的东西?任何帮助表示赞赏!
解决方法
fromEntries
是Object
本身的一种方法-它不在Object.prototype
上,因此在正常情况下,没有对象会在其原型链中包含Object.fromEntries
。>
类似地,将属性设置为Parent不会将其放入原型链中:
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);
Parent.STATIC_PROPERTY = 'static property';
const c = new Child('somename',5);
for (const prop in c) {
console.log(prop);
}
如果该方法位于Object.prototype
上,它将将放在原型链中,并且您可以覆盖该描述符,以便在遍历普通对象时可以看到该描述符。这是为Object.prototype.hasOwnProperty
执行此操作的示例:
function Parent(name) {
this.name = name;
}
Parent.prototype.sex = "Male";
function Child(name,name);
this.age = age;
}
Child.prototype = Object.create(Parent.prototype);
const { hasOwnProperty } = Object.prototype;
Object.defineProperty(Object.prototype,"hasOwnProperty",{
value: hasOwnProperty,enumerable: true,});
for (const key in new Child('name',5)) {
console.log(key);
}
或者,稍微简单一点:
function Parent(name) {
this.name = name;
}
Parent.prototype.sex = "Male";
function Child(name,name);
this.age = age;
}
Child.prototype = Object.create(Parent.prototype);
const { hasOwnProperty } = Object.prototype;
delete Object.prototype.hasOwnProperty;
Object.prototype.hasOwnProperty = hasOwnProperty;
for (const key in new Child('name',5)) {
console.log(key);
}
(不是要覆盖原始原型,这只是为了说明游戏中的机制)
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。