今天我注意到 hasOwnProperty
方法有一些奇怪的行为。
我在完全支持 ES6 类的环境中,因此无需担心转换。
上面的代码片段应该分别返回 true 和 false,但它在两者上都返回 true。
class Stuff {
constructor() { this.something = 'something'; }
}
class MoreStuff extends Stuff {}
const stuff = new Stuff();
const moreStuff = new MoreStuff();
console.log(Object.prototype.hasOwnProperty.call(stuff, 'something'));
console.log(Object.prototype.hasOwnProperty.call(moreStuff, 'something'));
也许我在这里遗漏了一些东西,但据我所知,东西上存在某些东西并且它在 moreStuff 上继承,但似乎两者都存在。 我缺少什么?
最佳答案
Stuff
构造函数将“something”属性直接放在构造的对象上。无论您是创建父类还是继承类的实例,都是如此。不涉及原型(prototype)链。
关于javascript - hasOwnProperty 是遍历原型(prototype)链,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56113060/