开发者

Do arrays have no prototype by default?

I was hoping to be able to augment Array.prototype with methods and then call them on any array:

>>> [1, 2, 3].customMethod();

But it appears arrays have no prototype...?

>>> [1, 2, 3].prototype
undefined

Am I missing something here?


It appears my actual problem lies elsewhere: calling [1, 2, 3].customMethod() works, but calling someDomElement.childNodes.customMethod() fails. Is childNodes not a real array?

childNodes.filter is not a func开发者_如何学JAVAtion


prototype is a property of constructor functions, like Array. So Array.prototype exists, but not [1, 2, 3].prototype; Array is a constructor function, while [1, 2, 3] is an array.

You are looking for Object.getPrototypeOf([1, 2, 3]).

Object.getPrototypeOf is an ECMAScript 5 method, and as such may not be present in all browsers. In which case, you can try accessing the __proto__ property, i.e. [1, 2, 3].__proto__, which is an older, nonstandard thing that Object.getPrototypeOf is the new standard version of, or you can use an ES5 shim to ensure that wherever __proto__ is supported, so is Object.getPrototypeOf.


It looks like you're working with a DOM NodeList, which is not the same thing as a JavaScript array object.

http://blog.duruk.net/2011/06/19/nodelists-and-arrays-in-javascript/ should provide some insight.

To obtain a 'real' javascript array from an Array-like object (such as a NodeList or the arguments variable), use the .slice method, like so:

var realArray = Array.prototype.slice.call(someDomElement.childNodes);
realArray.filter()

And yes, like another answer indicated - the .prototype object is only a property of the constructor function - not of instances. eg. Object.prototype exists, but ({}).prototype is undefined.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜