最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Does JavaScript's for in loop iterate over methods? - Stack Overflow

programmeradmin4浏览0评论

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"]

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"]
Share Improve this question asked Mar 30, 2010 at 1:40 hekevintranhekevintran 23.7k34 gold badges115 silver badges182 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 12

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/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 bee 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"]

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.

发布评论

评论列表(0)

  1. 暂无评论