Try and do the following:
for (var key in String.prototype)
console.log(key);
It gives you...nothing (well, unless you defined some foreign stuff yourself.) However, you still have String.prototype.split
for example. I tried it on every other native object (Number
, Array
, Object
) for the same result.
The following also "doesn't work":
for (var key in Array)
console.log(key);
While there's Array.isArray
for exam开发者_Python百科ple.
Object.keys(Array.prototype)
gives an empty array, and so does Object.keys(Array)
. However, Object.keys(jQuery)
for example provides a giant array, as expected.
So, why can't we iterate over natives provided by the browser, yet still access them?
From the MDC page for for..in
:
A
for...in
loop does not iterate over built-in properties
The reason is that properties in Javascript are either enumerable or non-enumerable; "enumerable" means you can access the property in a for..in
loop. All built-in properties are non-enumerable.
Modern browsers support the Object.getOwnPropertyNames
method:
console.log(Object.getOwnPropertyNames(Array.prototype));
// ["length", "constructor", "concat", "map", "sort", "join", "indexOf", "filter", "some", "toString", "reduceRight", "splice", "forEach", "shift", "unshift", "toLocaleString", "lastIndexOf", "reverse", "reduce", "pop", "push", "every", "slice"]
精彩评论