数组默认没有原型吗?
我希望能够用方法增强 Array.prototype ,然后在任何数组上调用它们:
>>> [1, 2, 3].customMethod();
但数组似乎没有原型......?
>>> [1, 2, 3].prototype
undefined
我在这里错过了什么吗?
看来我的实际问题出在其他地方:调用 [1, 2, 3].customMethod()
有效,但调用 someDomElement.childNodes.customMethod()
失败。 childNodes
不是一个真正的数组吗?
childNodes.filter is not a function
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 function
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
prototype
是构造函数的一个属性,就像Array
一样。所以Array.prototype
存在,但[1, 2, 3].prototype
不存在;Array
是一个构造函数,而[1, 2, 3]
是一个数组。您正在寻找
Object.getPrototypeOf([1, 2, 3])
。Object.getPrototypeOf
是一个 ECMAScript 5 方法,并且作为这可能并不存在于所有浏览器中。在这种情况下,您可以尝试访问__proto__
属性,即[1, 2, 3].__proto__
,这是一个较旧的、非标准的东西Object. getPrototypeOf
是新的标准版本,或者您可以使用 ES5 shim 来确保只要支持__proto__
,Object.getPrototypeOf
也支持。prototype
is a property of constructor functions, likeArray
. SoArray.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 thatObject.getPrototypeOf
is the new standard version of, or you can use an ES5 shim to ensure that wherever__proto__
is supported, so isObject.getPrototypeOf
.看起来您正在使用 DOM NodeList,这与 JavaScript 数组对象不同。
http://blog.duruk.net/2011/ 06/19/nodelists-and-arrays-in-javascript/ 应该提供一些见解。
要从类似数组的对象(例如
NodeList
或arguments
变量)获取“真正的”javascript 数组,请使用.slice
方法,如下所示:是的,就像另一个答案所示 -
.prototype
对象只是构造函数的属性 - 而不是实例的属性。例如。Object.prototype
存在,但({}).prototype
未定义。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 thearguments
variable), use the.slice
method, like so: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.