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] {}
举个例子,我得了Object.prototype
分,而不是null
分.
实际上,如果不是Object,它对每个值都有效,例如,这里的[[Prototype]]
of obj也是Object.prototype
:
function Rabbit() {
this.name = 'rabbit';
}
Rabbit.prototype = 5; // *
let obj = new Rabbit();
console.log(Object.getPrototypeOf(obj)); // [Object: null prototype] {}
当我有对象.prototype
时,它就会正常工作:
function Rabbit() {
this.name = 'rabbit';
}
Rabbit.prototype = {
eats: true,
}; // *
let obj = new Rabbit();
console.log(Object.getPrototypeOf(obj)); // { eats: true }
那么,为什么会是这样呢?我是不是搞错了,不明白什么?