Why a prototype is not available in a simple JavaScript object

I am trying to understand the JavaScript prototype and I'm a little confused. There are many textbooks there, and each has different explanations. So I don’t know where to start.

So far I have created a simple JavaScript object

var a = {flag : 1} 

At MDN , I read that

All objects in JavaScript come from Object

But I could not find a prototype for this object a a.prototype gives me undefined

Then I found that the prototype is available in a.constructor.prototype . When I create the var myfunc = function() {} function var myfunc = function() {} and then myfunc.prototype . Thus, the prototype property is available directly to functions, and not to objects.

Please help me understand this and what is a.constructor .

Any help is greatly appreciated.

+5
source share
2 answers

Each function can be called as a constructor (with the new keyword).

 function Dog() { this.legs = 4; } 

When you call it as a regular function, var dog = Dog() , it will define window.legs in browsers as 4 (something a little different, but related if in Node.JS), and set dog to undefined .

However, if you call it a constructor like var dog = new Dog() , it will create a new object and set its constructor to this function and assign this new dog object. It will install its internal prototype (which in some browsers can be accessed as dog.__proto__ ) to the prototype constructor ( Dog.prototype ). Or, in pseudo code,

 var dog = { legs: 4 }; dog.constructor = Dog; dog.__proto__ = Dog.prototype; // same as dog.constructor.prototype 

Thus, dog.constructor.prototype not, strictly speaking, the prototype of dog , it is an object that will be assigned to the prototype when the constructor function is launched. And, in particular, Dog.prototype not a prototype of the dog function (only the prototype that its instances will acquire). The reason prototype not available for non-functions, because non-functions cannot be used as constructors, so it makes no sense to have it (since its only function should be copied to the constructed objects of the __proto__ instance).

The object in your example still has a prototype but is not directly accessible; you can either go the hacker route in browsers that allow it ( a.__proto__ ), or request a browser ( Object.getPrototypeOf(a) ).

+1
source

You can use Object.getPrototypeOf() to return a prototype of Object to you.

To see this in your devtools browser, follow these steps:

 var a = {flag: 1}; console.dir(Object.getPrototypeOf(a)); 
+2
source

All Articles