我目前正在 javascript.info 上学习 JavaScript,我发现了这样的说法:
声明链接:
声明
但是当我在构造函数的
null
中使用 .prototype
尝试此代码时:
function Rabbit() {
this.name = 'rabbit';
}
Rabbit.prototype = null; // *
let obj = new Rabbit();
console.log(Object.getPrototypeOf(obj)); // [Object: null prototype] {}
我得到
Object.prototype
作为实例的 [[Prototype]]
,而不是 null
。 [[Prototype]]
也将是 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 }
那么为什么会这样呢?我是不是错了,不明白什么?
设置除对象之外的构造函数的
.prototype
属性的任何值,当使用 Object.prototpe
关键字调用构造函数时,会自动将 new
设置为结果对象的原型。
来自 MDN - 功能:原型:
如果函数的原型被重新赋值为 Object 以外的东西,那么当使用 new 调用该函数时,返回的对象的原型将是 Object.prototype