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?
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.
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).
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With