一、prototype 是什么?
prototype
是每个函数(不包括箭头函数)都默认具有的属性,默认值为:指向函数本身的 constructor 对象。
1、查看 prototype
// 缺省值为:Rabbit.prototype = { constructor: Rabbit }
function Rabbit() { }
alert(Rabbit.prototype.constructor == Rabbit)
// rabbit继承了constructor
let rabbit = new Rabbit();
// 输出结果:true
alert(rabbit.constructor == Rabbit);
2、错误修改 prototype
对 prototype
不正确的修改,会导致 constructor
的改变。
function Rabbit() { }
// 1、错误:这会覆盖整个 Rabbit.prototype,
// Rabbit.prototype.constructor不能正确指向Rabbit
Rabbit.prototype = {
jumps: true
};
// 输出:false
alert(Rabbit.prototype.constructor === Rabbit);
3、正确修改 prototype
为了保持constructor的正确性,不要覆盖prototype,而是用添加和删除操作
function Rabbit() { }
// 1、正确:采用添加操作
// Rabbit.prototype.constructor==Rabbit没有被破坏
Rabbit.prototype.jumps = true
// 输出:true
alert(Rabbit.prototype.constructor === Rabbit);
// 2、正确:采用手动添加操作,等同于上面
Rabbit.prototype = {
jumps: true,
constructor: Rabbit
};
alert(Rabbit.prototype.constructor === Rabbit);
4、用 constructor
创建对象
function Rabbit(name) {
this.name = name;
alert(name);
}
let rabbit = new Rabbit("White Rabbit");
// constructor默认指向函数本身,上面和下面都是调用函数Rabbit创建对象
let rabbit2 = new rabbit.constructor("Black Rabbit");