|
一、原型继承:
特点:1、子类的原型指向父类的一个实例既可,会覆盖子类本身的属性(并不是直接复制父中的 属性和方法) 2、原型继承是把父类中的私有的以及共有的属性和方法当做子类中公有的 3、子类可以修改父类原型上的属性和方法,这样操作后可能会影响到父类的其他实例; 例: function Parent(){
this.x=100;
}
Parent.prototype.getX=function(){
console.log(this.x)
};
function Children(){
this.x=200;
}
Children.prototype=new Parent;
var c=new Children;
二、call继承: 特点:1、在子类的函数体中,把父类当做一个普通的函数执行,call继承直接复制了父类私有的 属性和方法到子类中为子类的私有属性和方法。 例: function Parent(){
this.x = 100;
this.writeX = function () {
}
}
Parent.prototype.getX =function () {
console.log(this.x);
};
function Children(){
Parent.call(this);
}
三、冒充对象继承: 特点:1、在子类的函数体中,创建一个父类的实例,将这个实例当做一个普通的对象进行遍历, 这样会把父类中私有的共有的属性和方法都复制给子类为子类的私有属性和方法(即全复制)。 例: function Parent(){
this.x = 100;
this.writeX = function () {
}
}
Parent.prototype.getX =function () {
console.log(this.x);
};
function Children(){
var temp=new Parent();
for(var key in temp){
this[key]=temp[key];
}
temp=null; // 将temp重置,便于下次创建实例时使用;
}
四、混合继承: 特点:1、一般为原型继承和call继承混合使用 例: function Parent() {
this.x = 100;
this.writeX = function () {}
}
Parent.prototype.getX =function () {
console.log(this.x);
};
function Children(){
Parent.call(this); // call继承了父类的私有属性和方法;
}
Children.prototype = new Parent; // 原型继承了父类的私有的共有的到子类中为公有; |
|