JavaScript 的 for in 循环会迭代方法吗?
在 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
所有用户定义的属性都是可枚举的,包括从原型继承的属性。内置的本机属性不是。 toString() 就是其中之一。请参阅此处 https://developer.mozilla.org/En/Core_JavaScript_1 .5_Reference/Statements/For...in
编辑:我对“但是,循环将迭代所有用户定义的属性(包括任何覆盖内置属性的属性)” properties)” 是直接在对象中被覆盖的属性变得可枚举。不是原型本身的覆盖。这意味着:
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...inEdit: 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:
for..in
迭代用户定义的属性。如果您将代码更改为:那么
将输出:
As Chetan Sastry 指出,
toString
的处理方式有所不同,因为它是内置的本机属性。for..in
iterates over user-defined properties. If you change your code to:Then
Will output:
As Chetan Sastry pointed pointed out,
toString
is treated differently since it is a built-in, native property.