Search code examples
javascriptprototype

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?


Solution

  • 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