1.什么是propotype
官方是这样解释propotype的:使你有能力向对象添加属性和方法
为了更好理解 我们直接用官方的例子来具体说明一下吧
function employee(name,job,born) {
this.name=name;
this.job=job;
this.born=born;
}
var bill = new employee("Bill Gates","Engineer",1985);
employee.prototype.salary=null;
bill.salary=20000;
document.write(bill.salary);
可以看出这里new了一个构造函数employee() 之后,employee.prototype就是它的原型对象,这里为原型对象添加了salary的属性,也就意味着employee这个构造函数新增了salary这个属性;然后当生成实例对象bill时,这个对象就有了salary属性。同理我们还可以添加方法,像下面这样,实例对象就有了work方法
employee.prototype.work = function () {
alert('work')
};
bill.work();
哈哈 ,到这你应该明白prototype的用途了吧!那我们再看看下面prototype还有哪些使用场景呢
2.prototype继承
直接上代码
function Parent() {
this.eat=function () {
alert('eat');
};
this.type = 'cool man'
}
function Child(name) {
this.name = name;
}
Child.prototype = new Parent();
var c1 = new Child('mike');
console.log(c1);
console.log(c1.type);
c1.eat();
打印c1可以看出chilid继承了Parent的type属性,还有它的eat方法
关于原型和原型链的概念,可以查看我之前写的关于js的原型,原型链
到这里原型和原型链你应该都了解了吧,嘻嘻