一、prototype 是什么?

prototype 是每个函数(不包含箭头函数)都默认具备的属性,默认值为:指向函数自身的 constructor 对象。


1、查看 prototype
// 缺省值为:Rabbit.prototype = { constructor: Rabbit }function Rabbit() { }alert(Rabbit.prototype.constructor == Rabbit)// rabbit继承了constructorlet rabbit = new Rabbit();// 输入后果:truealert(rabbit.constructor == Rabbit);

2、谬误批改 prototype

prototype 不正确的批改,会导致 constructor 的扭转。

function Rabbit() { }// 1、谬误:这会笼罩整个 Rabbit.prototype,// Rabbit.prototype.constructor不能正确指向RabbitRabbit.prototype = {    jumps: true};// 输入:falsealert(Rabbit.prototype.constructor === Rabbit);

3、正确批改 prototype

为了放弃constructor的正确性,不要笼罩prototype,而是用增加和删除操作

function Rabbit() { }// 1、正确:采纳增加操作// Rabbit.prototype.constructor==Rabbit没有被毁坏Rabbit.prototype.jumps = true// 输入:truealert(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");

二、参考链接
  • JavaScript的prototype是什么?