【问题标题】:JavaScript overwrite Object property enumerability still not enumerableJavaScript 覆盖对象属性可枚举性仍然不可枚举
【发布时间】: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


【解决方案1】:

同样,在 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, age) {
  Parent.call(this, 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, age) {
  Parent.call(this, 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);
}

(不应该覆盖原生原型 - 这只是为了说明游戏中的机制)

【讨论】:

    猜你喜欢
    • 2012-05-02
    • 2012-05-03
    • 2018-12-18
    • 2013-05-18
    • 2021-08-08
    • 1970-01-01
    • 2017-03-05
    • 1970-01-01
    相关资源
    最近更新 更多