hasOwnProperty正在遍历原型链

丹尼尔515

今天,我注意到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上继承的,但是似乎两者都存在。我缺少什么?

间隔

在您的承包商中,何时执行以下操作:

this.something = 'something';

您将那个值放入对象而不是原型中。

即使您是子类,构造函数也会将的值添加'something'到对象中。

如果要在原型上使用它,则必须将其设为静态:

class Stuff {
  static get something() {
    return 'something';
  }
  
  constructor() {
    this.ownProp = true;
  }
}
Stuff.somethingElse = 'somethingElse';

class MoreStuff extends Stuff {}
const stuff = new Stuff();
const moreStuff = new MoreStuff();

console.log(stuff.hasOwnProperty('something'));
console.log(stuff.hasOwnProperty('somethingElse'));
console.log(stuff.hasOwnProperty('ownProp'));
console.log(moreStuff.hasOwnProperty('something'));
console.log(moreStuff.hasOwnProperty('somethingElse'));
console.log(moreStuff.hasOwnProperty('ownProp'));

ownProp仍然是实例的属性,其中somethingsomethingElse是Class(原型)的属性

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章