您的位置:首页 > Web前端 > JavaScript

javascript 学习笔记(5)---继承

2010-04-19 21:51 603 查看
1. 某些基类如果不直接使用,而仅仅只是用于给子类提供通用的函数,这种情况下,基类被看作抽象类.

2. 在 javascript 的类中所有的方法和属性都是"公用的".

3. javascript 中的继承并不是明确规定的,而是通过模仿来实现的.有以下方法:

(1). 对象冒充

function A(sColor){
this.color = sColor;
this.showColor = function(){
alert(this.color);
};
}
function B(sColor,sName){
this.newMethod = A;
this.newMethod(sColor);
delete this.newMethod;
this.name = sName;     //新的方法和属性要在删除了新方法的定                    义后定义
this.showName = function(){
alert(this.name);
};
}
 

        对象冒充方法可以支持多重类继承,也就是一个类可以继承于多个类

        如果存在一个类 C 想继承类 A 和 B,只要这样:

                
function C(){
this.newMethod = A;
this.newMethod();
delete this.newMethod
this.newMethod = B;
this.newMethod();
delete this.newMethod
}
 

       但是要注意如果 A 和 B 中存在同名的属性或者方法,则 B 具有高优先级,因为他是后面的类继承.

     (2). call() 方法

                
function B(sColor,sName){
//this.newMethod = A;
//this.newMethod(sColor);
//delete this.newMethod;
A.call(this,sColor);
this.name = sName;
this.showName = function(){
alert(this.name);
};
}
 

      (3). apply() 方法

                
function B(sColor,sName){
//this.newMethod = A;
//this.newMethod(sColor);
//delete this.newMethod;
A.apply(this,new Array(sColor));
this.name = sName;
this.showName = function(){
alert(this.name);
};
}
 

       (4). 原型链,原型链不支持多重继承

                
function A(){
}
A.prototype.color = "red";
A.prototype.showColor = function(){
alert(this.color);
}
function B(){
}
B.prototype = new A();
 

       原型链中 instanceof 运算符的运行方式也很特别,对 B 的所有实例,instanceof 为 A 和 B 都返回 true

                
var Obj = new B();
alert(Obj instanceof A);  //outputs "true"
alert(Obj instanceof B);  //outputs "true"
 

        (5)混合方式(对象冒充(属性)+原型链(方法))

                
function A(sColor){
this.color = sColor;
}
A.prototype.showColor = function(){
alert(this.color);
};
function B(sColor,sName){
A.call(this,sColor);
this.name = sName;
}
B.prototype = new A();
B.prototype.showName = function(){
alert(this.name);
};
 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  javascript function delete c