//1、工厂模式
function createCar(){
var car = new Object();
car.color="red";
car.doors=4;
car.mpg=23;
car.showColor=function(){
alert(this.color);
}
return car
}
/*
由于上述创建的对象的属性都一样,所以可以通过参数化实现不一样
*/
function createCar(sColor,iDoor,iMpg){
var car = new Object();
car.color=sColor;
car.doors=iDoor;
car.mpg=iMpg;
car.showColor=function(){
alert(this.color);
}
return car
}
//以上这种方式创的每一个对象都创建了showColor方法,所以造成重复
function showColor(){
alert(this.color);
}
function createCar(sColor,iDoor,iMpg){
var car = new Object();
car.color=sColor;
car.doors=iDoor;
car.mpg=iMpg;
car.showColor=showColor;
return car
}
//2、构造函数方式
function createCar(sColor,iDoor,iMpg){
this.color = sColor;
this.iDoor = iDoor;
this.iMpg = iMpg;
this.showColor=function(){
alert(this.color)
}
}
//3、原型模式
function car(){}
car.prototype.color="red";
car.prototype.Door=4;
car.prototype.mpg=23;
car.prototype.showColor=function(){
alert(this.color);
}
//但是这种模式有一个特点就是创建出来的每一个对象的属性都一样
//4、构造函数/原型混合模式
function car(iColor,sDoor,iMpg){
this.color=iColor;
this.doors=sDoor;
this.mpg=iMpg;
}
car.prototype.showColor=function(){
alert(this.color);
}
//5、动态原型模式
function car(icolor,sdoor,impg){
this.color=icolor;
this.sdoor=door;
this.impg=mpg;
if(typeof car._initialized=="undefined"){
car.prototype.showColor=function(){
alert(this.color)
}
}
car._initialized=true;
}
//6、混合模式
//混合模式的定义方法跟工厂模式很像,但是实例化是却不同,工厂模式不需要new,但是混合模式需要new操作符
//继承的几种方式
//1、对象冒充
function ClassA(sColor){
this.color=sColor;
this.sayColor=function(){
alert(this.color);
}
}
//所有的新的属性和方法必须在删除方法后
function ClassB(sColor,sName){
this.newMethod=ClassA;
this.newMethod=(sColor);
delete this.newMethod;
this.name=sName;
this.sayName = function(){
alert(sName);
}
}
//2、call方法
function ClassB(sColor,sName){
ClassA.call(this,sColor);
this.name=sName;
this.sayName=function(){
alert(sName);
}
}
//3、apply方法
function ClassB(sColor,sName){
ClassA.apply(this,new Array(sColor))
this.sName=sName;
this.sayName=function(){
alert(this.name);
}
}
//或者用arguments
function ClassB(sColor,sName){
ClassA.apply(this,arguments)
this.sName=sName;
this.sayName=function(){
alert(this.name);
}
}
//4、原型链
function ClassA(){}
ClassA.prototype.color="red";
ClassA.prototype.sayColor=function(){
alert(color);
}
function ClassB(){}
ClassB.prototype= new ClassA();
ClassB.prototype.name="";
ClassB.prototype.sayName = function(){
alert(this.name);
}
//5、混合方式
function ClassA(sColor){
this.color=sColor;
}
ClassA.prototype.showColor=function(){
alert(this.color);
}
function ClassB(sColor,sName){
ClassA.call(this,sColor);
this.name=sName;
}
ClassB.prototype=new ClassA();
ClassB.prototype.sayName=function(){
alert(this.name)
}