javascript高级程序设计学习(四)----------继承

    继承是面向对象程序设计中的重要部分,javaScript 实现继承的方式不止一种。这是因为 JavaScript 中的继承机制并不是明确规定的,而是通过模仿实现的.

1.对象冒充

        可以实现,多重继承。新属性要写在delete后面。

function classA(sId)
{  this.id=sId; 
    this.showId=function(){alert(this.id)}
}

function classB(sId,sName)
{
  this.newMethod=classA;
  this.newMethod(sId);
  delete this.newMethod;//继承classA
 
   this.name=sName;
  this.showName=function()
       {alert(this.name)}
}


2.Call/Apply方法。

    如上例将有newMethod的三行换成, classA.call(this, sId) 或 classA(this,  new Array(sId)) ;就可以实现继承。


3、原型链

    原型链最大的缺点是不能传递参数。


function classA(){
  }
  classA.prototype.id="4";
  classA.prototype.showId=function(){ alert(this.id); }
  function classB(){}
  classB.prototype=new classA();
  var b=new classB();
  var a=new classA();
  a.showId();
  b.showId();
  

与对象冒充相似,子类的所有属性和方法都必须出现在 prototype 属性被赋值后,因为在它之前赋值的所有方法都会被删除。为什么?因为 prototype 属性被替换成了新对象,添加了新方法的原始对象将被销毁。所以,为 ClassB 类添加 name 属性和 showName() 方法的代码如下:


function ClassB() {
}

ClassB.prototype = new ClassA();

ClassB.prototype.name = "";
ClassB.prototype.showName = function () {
    alert(this.name);
};

4.混合方式

   对属性用Call, 对方法用prototype.

function ClassA(sId) {
    this.id = sId;
}

ClassA.prototype.showId = function () {
    alert(this.id);
};
function ClassB(sId, sName) {
    ClassA.call(this, sColor);
    this.name = sName;
}
ClassB.prototype = new ClassA();

ClassB.prototype.showName = function () {
    alert(this.name);
};

参考图书:<<javascript高级程序设计>>




评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值