Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is JavaScript prototype property undefined on new objects?

I'm fairly new to the concept of JavaScript's prototype concept.

Considering the following code :

var x = function func(){ }  x.prototype.log = function() {   console.log("1"); }  var b = new x(); 

As I understand it, b.log() should return 1 since x is its prototype. But why is the property b.prototype undefined?

Isn't b.prototype supposed to return the reference to the x function?

like image 313
Pascal Paradis Avatar asked Jan 22 '13 02:01

Pascal Paradis


People also ask

Why is object prototype undefined?

Only constructor functions have prototypes. Since x is a constructor function, x has a prototype. b is not a constructor function. Hence, it does not have a prototype.

Why this is undefined in an object JavaScript?

In JavaScript there is null and there is undefined. They have different meanings. undefined means that the variable value has not been defined; it is not known what the value is. null means that the variable value is defined and set to null (has no value).

Do all JavaScript objects have a prototype property?

Each and every JavaScript function will have a prototype property which is of the object type. You can define your own properties under prototype . When you will use the function as a constructor function, all the instances of it will inherit properties from the prototype object.

Do objects have prototype property?

Conceptually, all objects have a prototype (NOT A PROTOTYPE PROPERTY). Internally, JavaScript names an object's prototype as [[Prototype]]. There are two approaches to get any object (including non-function object)'s [[prototype]]: the Object. getPrototypeOf() method and the __proto__ property.


1 Answers

Only constructor functions have prototypes. Since x is a constructor function, x has a prototype.

b is not a constructor function. Hence, it does not have a prototype.

If you want to get a reference to the function that constructed b (in this case, x), you can use

b.constructor 
like image 141
Peter Olson Avatar answered Oct 08 '22 23:10

Peter Olson