首页 > 其他 > 详细

主要继承方式

时间:2015-10-20 12:03:30      阅读:282      评论:0      收藏:0      [点我收藏+]

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"

 

主要继承方式

原文:http://www.cnblogs.com/yzg1/p/4894020.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!