javascript中类继承的几中的几种方法

本文深入探讨了ECMAScript中多种继承实现方式,包括对象冒充、使用call()和apply()方法以及原型链等,并提供了具体代码示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

以下摘《Javascript程序高级设计》一书,有改动.

ECMAScript中的继承的方式不止一种。这是因为javascript中的继承机制并不是明确规定的,而是通过模仿实现的。

1.对象冒充方式
    

function classA(sColor){
    
this.color=sColor;
    
this.sayColor=function(){
        alert(
this.color);
    }
;
}


function classB(sColor)
{
    
this.newMethod=classA;
    
this.newMethod(sColor);
    delete 
this.newMethod;
}


var b
=new classB("red");
b.sayColor();

//所有的新属性和新方法都必须在删除了新方法的代码后定义,否则,可能会覆盖超类的相关属性和方法

有趣的是,对象冒充可以支持多重继承:
function classZ(){
    
this.newMethod=classX;
    
this.newMethod();
    delete 
this.newMethod;

    
this.newMethod=classY;
    
this.newMethod();
    delete 
this.newMethod;
}


//如果classX和classY,具有同名的属性或方法,classY会有高优先级。

在是因为这种继承方法的流行,ECMAScript的第三版为Function对象加入了两个新方法,即call()和apply()。

2,Call()方法

//测试call
function sayHello(){
    alert(
this.msg);
}


var h
={msg:"helloWorld!"};
sayHello.call(h);

//
function classA(sColor){
    
this.color=sColor;
    
this.sayColor=function(){
        alert(
this.color);
    }
;
    
}


function classB(sColor)
{
    classA.call(
this,sColor);
}


var b
=new classB("red");
b.sayColor();

3.apply()方法
apply()方法有两个参数,用作this的对象和要传递给函数的参数的数组。

function classB(sColor){
    classA.apply(
this.new Array(sColor));
}


4.原形链
    prototype对象是一个模板,要实例化的对象都以这个模板为基础,况而言之,prototyp对象的任何属性和方法都被传递给那个类的所有实例。原形链利用这种功能来实现继承机制。

function classA(sColor){
    
this.color=sColor;
    
this.sayColor=function(){
        alert(
this.color);
    }
;
    
}

function classB(){}
classB.prototype
=new classA("red")
//继续定义classB的相关属性或方法
classB.prototype.version="1.0";
classB.prototype.setMsg
=function(msg){
    alert(msg
+this.version);
}
;

var b=new classB();
b.setMsg(
"china");

//注意,调用ClassA的构造函数时,没有给它传递参数。这是原型链中是标准做法。要确保构造函数没有任何参数。

 

 javascript 高级程序设计一书封面

 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值