关于javascript:JavaScript的prototype是什么

一、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");

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

评论

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

这个站点使用 Akismet 来减少垃圾评论。了解你的评论数据如何被处理