1.构造函数绑定
将父对象的构造函数绑定到子对象
function Child(){
Parent.apply(this,arguments);
}
2.prototype模式
使用prototype属性
Child.prototype = new Parent()
Child.prototype.constructor = Child
每一个实例也有一个constructor属性,默认调用prototype对象的constructor属性。
prototype发生改变后,要将其constructor指向原构造函数。
3.直接继承prototype
将Child的prototype对象,然后指向Parent的prototype对象,这样就完成了继承。
Child.prototype = Parent.prototype
Child.prototype.constructor = Child
4.利用空对象做中介
function extend(Child, Parent) {
var F = function() {};
F.prototype = Parent.prototype;
Child.prototype = new F();
Child.prototype.constructor = Child;
}
F是空对象,所以几乎不占内存。这时,修改Child的prototype对象,就不会影响到Parent的prototype对象。
5.拷贝继承
function extend2(Child, Parent) {
var c = Child.proptotype;
var p = Parent.prototype;
for (var i in p) {
c[i] = p[i];
}
}
这个函数的作用,就是将父对象的prototype对象中的属性,一一拷贝给Child对象的prototype对象。