(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;