Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why null doesn't work in .prototype of constructor

I am currently learning JavaScript on javascript.info and I came across this statement:
Statement
Link to the statement:
statement
But when I try this code with null in .prototype of constructor:

function Rabbit() {
    this.name = 'rabbit';
}

Rabbit.prototype = null; // *

let obj = new Rabbit();

console.log(Object.getPrototypeOf(obj)); // [Object: null prototype] {}

I get Object.prototype as a [[Prototype]] of instance and not null.
And actually it works for every value if it’s not object, for example here [[Prototype]] of obj will be also Object.prototype:

function Rabbit() {
    this.name = 'rabbit';
}

Rabbit.prototype = 5; // *

let obj = new Rabbit();

console.log(Object.getPrototypeOf(obj)); // [Object: null prototype] {}

And when I have object .prototype it works as it should:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

function Rabbit() {
    this.name = 'rabbit';
}

Rabbit.prototype = {
    eats: true,
}; // *

let obj = new Rabbit();

console.log(Object.getPrototypeOf(obj)); // { eats: true }

So why it works like that? Am I wrong and don’t understand something?

>Solution :

Setting any value of .prototype property of a constructor function other than an object automatically sets Object.prototpe as the prototype of the resulting object when the constructor functions is called with new keyword.

From MDN – Function: prototype:

If the prototype of a function is reassigned with something other than an Object, when the function is called with new, the returned object’s prototype would be Object.prototype instead. (In other words, new ignores the prototype property and constructs a plain object.)

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading