阿尔卑斯丶
圣骑士
圣骑士
  • 最后登录2023-11-03
  • 发帖数59
  • 社区居民
  • 原创写手
阅读:5535回复:0

[js]函数的继承

楼主#
更多 发布于:2018-08-28 18:39
一、原型继承:
特点: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; // 原型继承了父类的私有的共有的到子类中为公有;
游客


返回顶部

公众号

公众号