JavaScript 的 for in 循环会迭代方法吗?

发布于 2024-08-26 21:10:27 字数 489 浏览 9 评论 0原文

在 yuiblog 上的一篇 文章 中,Douglas Crockford 说for in 语句将迭代对象的方法。为什么以下代码不生成 ["a", "b", "c", "d", "toString"]? .toString() 和其他方法不是 my_obj 的成员吗?

Object.prototype.toString = function(){return 'abc'}
Object.prototype.d = 4;

my_obj = {
    'a':1,
    'b':2,
    'c':3
}

a = []
for (var key in my_obj) {
    a.push(key)
}

console.log(a) // prints ["a", "b", "c", "d"]

In an article on yuiblog Douglas Crockford says that the for in statement will iterate over the methods of an object. Why does the following code not produce ["a", "b", "c", "d", "toString"]? Aren't .toString() and other methods members of my_obj?

Object.prototype.toString = function(){return 'abc'}
Object.prototype.d = 4;

my_obj = {
    'a':1,
    'b':2,
    'c':3
}

a = []
for (var key in my_obj) {
    a.push(key)
}

console.log(a) // prints ["a", "b", "c", "d"]

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

︶葆Ⅱㄣ 2024-09-02 21:10:27

所有用户定义的属性都是可枚举的,包括从原型继承的属性。内置的本机属性不是。 toString() 就是其中之一。请参阅此处 https://developer.mozilla.org/En/Core_JavaScript_1 .5_Reference/Statements/For...in

编辑:我对“但是,循环将迭代所有用户定义的属性(包括任何覆盖内置属性的属性)” properties)” 是直接在对象中被覆盖的属性变得可枚举。不是原型本身的覆盖。这意味着:

var my_obj = {a: 1, b: 2, c: 3};
my_obj.toString = function() {return 'abc';};

a = []
for (var key in my_obj) {
    a.push(key)
}

console.log(a) // prints ["a", "b", "c", "toString"]

All user defined properties are enumerable, including the properties inherited from prototype. The built-in native properties are not. toString() is one of them. See here https://developer.mozilla.org/En/Core_JavaScript_1.5_Reference/Statements/For...in

Edit: My interpretation of "However, the loop will iterate over all user-defined properties (including any which overwrite built-in properties)" is that the properties that are overwritten directly in the object become enumerable. Not the overwrite in the prototype itself. That means:

var my_obj = {a: 1, b: 2, c: 3};
my_obj.toString = function() {return 'abc';};

a = []
for (var key in my_obj) {
    a.push(key)
}

console.log(a) // prints ["a", "b", "c", "toString"]
甜点 2024-09-02 21:10:27

for..in 迭代用户定义的属性。如果您将代码更改为:

Object.prototype.foo = function() { return 'abc'; };

那么

console.log(a);

将输出:

["a", "b", "c", "foo", "d"]

As Chetan Sastry 指出,toString 的处理方式有所不同,因为它是内置的本机属性。

for..in iterates over user-defined properties. If you change your code to:

Object.prototype.foo = function() { return 'abc'; };

Then

console.log(a);

Will output:

["a", "b", "c", "foo", "d"]

As Chetan Sastry pointed pointed out, toString is treated differently since it is a built-in, native property.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文