JavaScript 中的继承(上)
发布日期:2021-10-01 08:44:33 浏览次数:4 分类:技术文章

本文共 1689 字,大约阅读时间需要 5 分钟。

    作者:
    继承是面向对象语言基本特征之一,通过继承可以将父类所具有的特性遗传到子类。ECMAScript中的继承不像Java、C++等语言那么明显,直接通过关键字来实现,通常它是通过模拟方式来实现继承功能的,并且实现方式有多种。
    在继承中引入this关键字,使用构造器方法定义类来实现继承。一个构造器是一个函数,因此可以将父类的构造器作为子类的一个方法使用并进行调用。
function
ClassA(id)
{
  
this .id = id;
  
this .sayId = function() {
     alert(
this.id);
   }
;
}
function ClassB(id, name) {
  
this .newMethod = ClassA;
  
this .newMethod(id);
  
delete this.newMethod;
  
this.name= name;
  
this.sayName= function(){
     alert(
this.name);
   }
;
}
    注意,子类中所有新的属性和方法都必需在删除newMethod后引入,否则,可能存在用父类的属性和方法重写子类属性和方法的危险。另外,使用这种方法还可以实现多重继承,此时如果两个父类具有相同的属性或方法时,最后的类具有优先级。由于这种继承方法比较流行,ECMAScript第三版引入了两个Function对象:call()和apply()。
    call()
    call()方法是最接近上述继承方式的方法,它的第一个参数是this指向的对象,所有的其他参数都直接传到function。
function
sayMessage(first, last) 
{
   alert(first
+ this.logic +last);
}
;
varobj =new Object();
obj.logic
= "or";
sayMessage.call(obj,
"Coffee ""Tea");  //输出"Coffee or Tea"
    用call()方法来实现继承,只需要this.newMethod相关的三行代码。
function
ClassB(id, name)
{
  
  //this.newMethod = ClassA;
  //this.newMethod(id);
  //delete this.newMethod;
  ClassA.call(this, id);  //this指向ClassB的对象
  
this.name =name;
  
this.sayName = function() {
     alert(
this.name);
   }
;
}
    apply()
    apply()方法需要两个参数:this所指向的对象,和传到function的由参数组成的array。
function
 sayMessage(first, last)  
{
  alert(first 
+
 
this
.logic 
+
last);
}
;
var
 obj 
=
 
new
 Object();
obj.logic 
=
 
"
or
"
;
sayMessage.apply(obj, 
new
 Array(
"
Coffee 
"
"
 Tea
"
));  
//
输出"Coffee or Tea"
  
    同样,使用 apply() 实现继承可以通过如下方法实现。
function
 ClassB(id, name) 
{
  
//this.newMethod = ClassA;
  //this.newMethod(id);
  //delete this.newMethod;
  ClassA.apply(thisnew Array(id));  //this指向ClassB的对象
  
this.name = name;
  
this.sayName = function() {
    alert(
this.name);
  }
;
}
    当父类构造器的参数和子类构造器参数的顺序一致时,可以使用子类的arguments对象作为第二个参数。否则,必需创建一个array来传递参数,或是使用call()方法。
   

转载地址:https://blog.csdn.net/iteye_263/article/details/81378547 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!

上一篇:JavaScript 中的继承(上)
下一篇:ArcIMS 体系结构

发表评论

最新留言

很好
[***.229.124.182]2024年04月19日 14时04分07秒

关于作者

    喝酒易醉,品茶养心,人生如梦,品茶悟道,何以解忧?唯有杜康!
-- 愿君每日到此一游!

推荐文章