一、为啥需要原型对象?
在实例的原型对象添加某个方法或者某个属性,可以达到不同实例的内存共享,减少内存浪费。
二、实现方式
(1)继承的第一种方式:原型链继承1
function Person(){
}
Person.prototype.say = function(){
console.log("你好");
}
var p1 = new Person();
var p2 = new Person();
console.log(p1.say === p2.say); // true
或者
function Person(){
}
var p1 = new Person();
var p2 = new Person();
Person.prototype.say = function(){
console.log("你好");
}
console.log(p1.say === p2.say); // true
上述例子:Person.prototype是p1和p2的原型对象或者Person.prototype是Person构造函数【实例】的原型对象。
说明一点:Person的原型对象是Function.prototype。
缺点:添加1、2个方法还好,但是如果方法很多会导致过多的代码冗余,于是产生了第二种方式。
(2)继承的第一种方式:原型链继承2
function Person(){
}
Person.prototype = {
constructor:Person,
say:function(){
console.log('你好');
}
}
var p1 = new Person();
var p2 = new Person();
console.log(p1.say === p2.say); // true
注意:
1. 一般情况下,应该先改变原型对象,再创建对象(new)。相反会导致原型对象上的方法或者属性变成undefined的。
2. 一般情况下,对于新原型,会添加一个constructor属性,从而不破坏原有的原型对象的结构。(可有可无,最好带上)