主要继承方式

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"

 

posted @ 2015-10-20 10:19  Bigdots  阅读(229)  评论(0编辑  收藏  举报