JavaScript 常见对象类创建代码与各自的优缺点分析
在javascript中的类定义方式,常用的是杂合prototype/constructor 和 动态prototype方式。
构建一个类有好几种方法:
1、Factory 方式
var car = new Object();
car.color=”b”;
car.length=1;
car.run=function(){alert(”run”);}
return car;
}
定义这么一个函数之后,就可以用:
var car2 = createCar();
来创建新的对象,这种方式的问题是每一次创建一个car对象,run Function也都必须重新创建一次,浪费内存。
2、Constructor方式
this.color=”b”;
this.length=1;
this.run=function(){alert(”run”);}
}
var car1=new Car();
var car2=new Car();
这是最基本的方式,但是也存在和factory方式一样的毛病。
3、prototype方式
}
Car.prototype.color=”b”;
Car.prototype.length=1;
Car.prototype.run=function(){alert(”run”);
}
此方式的缺点:当这个类有一个引用属性时,改变一个对象的这个属性也会改变其他对象得属性。
例如:
var car1=new Car();
var car2=new Car();
car1.data1.push(”a”);
此时,car2.data也就包含了”a”元素。
4、Prototype/Constructor杂合方式 也是最常用的方式
this.color=”b”;
this.length=1;
this.data1=new Array();
}
Car.prototype.run=function(){
alert(”dddd”);
}
摒弃了以上其它方式的缺点,是目前比较大范围使用的方式。
5、动态prototype方式 也很常用
function Car(){
this.color=”b”;
this.length=1;
this.data1=new Array();
if(typeof Car.initilize==”undefined”){
Car.prototype.run=function(){alert(”a”);}
}
Car.initilize=true;
}
总结:
以上几种方式中,最常用的是杂合prototype/constructor 和 动态prototype方式。
希望以上内容,有助于大家理解javascript对象类的创建方法,教程集,祝大家学习进步。
您可能感兴趣的文章:
JavaScript 常见对象类创建代码与各自的优缺点分析
Golang垃圾回收机制
mysql索引的建立原则
golang 面试题(四)go的组合继承
为什么要学 Go
mysql索引创建方法 mysql数据库索引例解
JavaScript 创建对象的例子
python c 和java的区别有哪些
python orm框架有哪些
引爆你的Javascript代码进化