I am currently learning JavaScript on javascript.info and I came across this 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:
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?
If you assign any value that is not an object to the prototype property of a function, the object created as a result of calling that function as a constructor function (with the new keyword) gets Object.prototype as its prototype.
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.)
If you want to ensure that the newly created object doesn't inherit anything from Object.prototype, you can use the Object.create as shown below:
Rabbit.prototype = Object.create(null);
This will set the prototype of Rabbit.prototype to null.
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