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

Javascript - Getting 'undefined' when trying to get array's prototype - Stack Overflow

programmeradmin4浏览0评论

I think its a 5am brain drain, but I'm having trouble with understanding this.

obj = ['a','b'];
alert( obj.prototype ); //returns "undefined"

Why isn't obj.prototype returning function Array(){ } as the prototype? It does reference Array as the constructor.

I think its a 5am brain drain, but I'm having trouble with understanding this.

obj = ['a','b'];
alert( obj.prototype ); //returns "undefined"

Why isn't obj.prototype returning function Array(){ } as the prototype? It does reference Array as the constructor.

Share Improve this question edited Sep 20, 2018 at 7:07 fabrik 14.4k8 gold badges57 silver badges71 bronze badges asked Mar 23, 2009 at 11:53 GeuisGeuis 42.3k57 gold badges163 silver badges223 bronze badges
Add a ment  | 

5 Answers 5

Reset to default 7

Because the instance doesn't have a prototype, the class* does.

Possibly you want obj.constructor.prototype or alternatively obj.constructor==Array

* to be more accurate, the constructor has the prototype, but of course in JS functions = classes = constructors

I'm not sure you can access the prototype object from an instance of an object. The following behaviour might help you:

alert(Array); // displays "function Array() { [native code] }"
alert(Array.prototype); // displays ""
alert(['a','b'].constructor); // displays "function Array() { [native code] }"

obj.prototype isn't returning function Array() { ... } as that is the object's constructor.

In your example, obj is an instance of an Array, not the class Array itself.

Another way to understand it is that for example, you can't inherit from an instance of an object (or class), you can only inherit from the object (or class) itself, which in your example it means that you could inherit from the Array object, but not from a direct instance of the Array object such as obj.

According to the ECMA spec, an object's prototype link isn't visible, but most modern browsers (firefox, safari, chrome) let you see it via the __proto__ property, so try:

obj = ['a','b'];
alert( obj.__proto__ );

An object also has the `constructor' property set on construction, so you can try:

obj = ['a','b'];
alert( obj.constructor.prototype );

However, obj.constructor can be changed after an object's contruction, as can obj.constructor.prototype, without changing the actual prototype pointer of obj.

Not really my cup of tea, but does this way of defining it make "obj" an array? Tried

obj = new Array();
obj[0] = "a";
obj[1] = "b";

?

发布评论

评论列表(0)

  1. 暂无评论