1.封装
function Car(sColor,iDoors,iMpg){
this.color = sColor;
this.doors = iDoors;
this.mpg = iMpg;
this.drivers = new Array("Mike","Sue");
if(typeof Car._initialized == "undefined"){
Car.prototype.showColor = function(){
alert(this.color);
}
Car._initialized = true;
}
}
2.继承
a.对象冒充
function ClassA(sColor){
this.color = sColor;
this.sayColor = function(){
alert(this.color);
};
}
function ClassB(sColor){
this.newMethod = ClassA;
this.newMethod(sColor);
delete this.newMethod;
this.name = sName;
this.sayName = function(){
alert(this.name);
};
}
var objA = new ClassA("red");
var objB = new ClassB("blue","Nicholas");
objA.sayColor(); // "red"
objB.sayColor(); // "blue"
objB.sayName(); // "Nicholas"
//注意:对象冒充可以实现多重继承
b.call()方法
function ClassB(sColor, sName){
//this.newMethod = ClassA;
//this.newMethod(sColor);
//delete this.newMethod;
ClassA.call(this,sColor);
this.name = sName;
this.sayName = function(){
alert(this.name);
};
}
c.apply()方法
function ClassB(sColor ,sName){
//this.newMethod = ClassA;
//this.newMethod(sColor);
//delete this.newMethod;
ClassA.apply(this, new Array(sColor));
this.name = sName;
this.sayName = function(){
alert(this.name);
};
}
d.混合方法
function ClassA(sColor){
this.color = sColor;
}
ClassA.prototype.sayColor = function(){
alert(this.color);
};
function ClassB(sColor ,sName){
ClassA.call(this,sColor);
}
ClassB.prototype = new ClassA();
ClassB.prototype.sayName = function(){
alert(this.name);
};