【发布时间】:2019-09-30 10:56:54
【问题描述】:
今天我注意到hasOwnProperty 方法的一些奇怪行为。
我在完全支持 ES6 类的环境中,所以不用担心转译。
上面的代码 sn-p 应该分别返回 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 上被继承,但似乎两者都存在。 我错过了什么?
【问题讨论】:
-
你为什么使用
call?Object.prototype.hasOwnProperty通常在类而不是实例上调用。 -
@evolutionxbox 不,倒退;它在实例上调用,如
stuff.hasOwnProperty("something") -
@Pointy 感谢您的澄清。在任何情况下您会使用
call和hasOwnProperty? -
好吧,我想不出有什么理由这样做。我不能肯定地说它从不有意义,但通常情况涉及对象引用,因此直接使用它同样容易。
-
在几种情况下,您不能依赖具有该方法的对象。
Object.create(null)、undefined或null是尝试直接调用该方法时会抛出的示例。
标签: javascript