gpt4 book ai didi

javascript - JavaScript 中的动态类型、扩展 Native 和 hasOwnProperty()

转载 作者:行者123 更新时间:2023-12-03 08:49:47 24 4
gpt4 key购买 nike

我在一本书中偶然发现了一段话,上面写着:

The hasOwnProperty() technique also requires the property name as a string and will check if an object has the property directly on that instance (and thus is not just an inherited prototype property).

好的,上面的行没有问题。

同一章后面的几行,

由于 JavaScript 是一种动态语言,我们可能会发现修改原生对象的原型(prototype)非常有用,尽管有点危险。

A very important note of warning should be stated here. The practice of extending the prototypes of native objects is both useful and dangerous. For example, it is commonly forbidden to extend the native Object prototype (from which all other objects inherit), useful as that may sound, because doing so causes those properties/methods to be seen in for-in loops that do not properly filter with hasOwnProperty().

当他提出这句话时,他实际上是什么意思,

... causes *those properties/methods to be seen in for-in loops that do not properly filter with ***hasOwnProperty()*...

因为,在上面所示的某个时刻,他说

hasOwnProperty()- will check if an object has the property directly on that instance

它们(原型(prototype)上定义的属性)如何无法正确过滤hasOwnProperty()

这两种说法是不是很矛盾?

您可以使用这个作为说明,

String.prototype.getThirdChar = function() {
return this.charAt(2);
};

然后,

var c = "Example".getThirdChar(); // c set to "a"

最佳答案

这个例子说明了问题:

// in some file far far away
Object.prototype.foo = function() {};

// in your own code
var obj = { bar: 'bar' };
for (var i in obj) {
console.log(i);
}

记录器将显示两个属性:bar(预期)和foo(可能不是,因为修改Object.prototype的代码通常是隐藏在某些实用程序模块中超出任何合理措施的范围)。原因?就这样:

Objects created from built–in constructors like Object have inherited non–enumerable properties from Object.prototype. The loop will iterate over all enumerable properties of the object itself and those the object inherits from its constructor's prototype (properties closer to the object in the prototype chain override prototypes' properties).

因此,如果您想迭代对象自己的属性,只需重新检查该属性的所有权即可:

for (var i in obj) if (obj.hasOwnProperty(i)) {
console.log(i); // just 'bar', nothing weird to see here, move along
}

请注意以下内容的区别:

关于javascript - JavaScript 中的动态类型、扩展 Native 和 hasOwnProperty(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32738375/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com