javascript 中的继承方式


(1)对象冒充
原理:A构造函数使用this 关键字给所有的属性和方法赋值,在别的函数B中调用他(因为它也只是个函数),B就会收到A中的所有属性和方法,即继承了A;

function FClassA(sColor){
   this.color = sColor;
   this.sayColor = function(){
    alert(this.color);
   };
}
function FClassB(sColor){
   this.newMethod = FClassA;//实现继承
   this.newMethod(sColor);
   this.sayColor = function(){
    alert("FClassB 's function");
   };
   delete this.newMethod;//删除对父类的引用后就不能在使用FClassA()函数了,但在FClassB中已经有了FClassA中所有的属性和方法
}
var FB = FClassB("Red");
FB.sayColor();//可以调用方法。
(2)call()方法
function sayColor(sPrefix, sSuffix){
   alert(sPrefix + this.color + sSuffix);
};
var obj = new Object();
obj.color = "red";
sayColor.call(obj, "The color is ",",a very nice color indeed.");//第一个参数为obj;!!!
//alert("The color is red a very nice color indeed.");

(3)apply()方法
function sayColor(sPrefix, sSuffix){
   alert(sPrefix + this.color + sSuffix);
};
var obj = new Object();
obj.color = "red";
sayColor.apply(obj, new Array("The color is ",",a very nice color indeed."));//第一个参数为obj;!!!
//alert("The color is red a very nice color indeed.");

(4)原型链方法 prototype 对象
function FClassA(){
}
FClassA.prototype.color="red";
FClassA.prototype.sayColor = function(){
   alert(this.color);
}
function FClassB(){
   this.i = 100;  
}
FClassB.prototype = new FClassA();
var objB = new FClassB();//有objA中的所有方法和属性
var objA = new FClassA();
注意:alert(objB instanceof FClassA);//true;
       alert(objA instanceof FClassA);//true;
(5)混合方式

======================================

The best way to create classes is to use the constructor paradigm to define the properties

and to user the proptotype paradigm to define methods.The same goes for inheritance;

you user object masquerading (伪装冒充) to inherit properties from constructor and prototype

chaning to inherit methods from the prototype object .

======================================
   function FClassA(sColor){
     this.color = sColor;
}
FClassA.prototype.sayColor = function(){
   alert(this.color);
};
function FClassB(sColor,sName){
   FClassA.call(this,sColor);//继承了FClassA的color属性
   this.name = sName;  
}
FClassB.prototype = new FClassA();//继承了FClassA中的所有
FClassB.prototype.sayName = function(){
     alert(this.name);
}
var objB = new FClassB();//有objA中的所有方法和属性
var objA = new FClassA();
alert(objB instanceof FClassA);//true;
alert(objA instanceof FClassA);//true;

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值