1.原型链继承

基本思想是利用原型让一个引用类型继承另一个引用类型的属性和方法;

function SuperType(){
  this.property = true;
}
SuperType.prototype.getSuperValue = function(){
  return this.property;
};
function SubType(){
  this.subproperty = false;
}
//继承了SuperType
SubType.prototype = new SuperType();
SubType.prototype.getSubValue = function (){
  return this.subproperty;
};
var instance = new SubType();
alert(instance.getSuperValue()); //true

 

2.构造函数

基本思想:在子类型构造函数的内部调用超类(父类)型构造函数,通过使用apply()和call()方法可以在(将来)新创建的对象上执行构造函数

每个函数都包含两个非继承而来的方法:apply()和call()。这两个方法的用途都是在特定的作用域中调用函数,实际上等于设置函数体内this 对象的值。

apply()和call()的功能一致,只是传递参数的方式不同:

apply(this,arguments)

call(this,argument1,argument2,argument3,...)

function SuperType(){
    this.colors = ["red", "blue", "green"];
}
function SubType(){
    //继承了SuperType
    SuperType.call(this);  // 设置superTpe函数体内this对象的值为subType函数
}
var instance1 = new SubType();
instance1.colors.push("black");
alert(instance1.colors); //"red,blue,green,black"
var instance2 = new SubType();
alert(instance2.colors); //"red,blue,green"

 

相关文章:

  • 2022-12-23
  • 2021-11-16
  • 2021-06-02
  • 2021-07-07
  • 2021-12-04
  • 2022-02-17
  • 2022-12-23
猜你喜欢
  • 2022-12-23
  • 2021-12-07
  • 2021-04-15
  • 2022-01-23
  • 2021-05-26
  • 2021-09-22
相关资源
相似解决方案