微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

JavaScript覆盖对象属性的可枚举性仍然无法枚举

如何解决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是不可配置的或类似的东西?任何帮助表示赞赏!

解决方法

fromEntriesObject本身的一种方法-它不在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 举报,一经查实,本站将立刻删除。