在Javascript中构建一个类有好几种方法:
1.Factory 方式
function createCar(){
  var car  =  new Object();
  car.color="b";
  car.length=1;
  car.run=function(){alert("run");}
  return car;
}
定义这么一个函数之后,就可以用:
var car1  =  createCar();
var car2  =  createCar();
来创建新的对象,这种方式的问题是每一次创建一个car对象,run Function也都必须
重新创建一次.浪费内存

2.Constructor方式
function Car(){
  this.color="b";
  this.length=1;
  this.run=function(){alert("run");}
}

var car1=new Car();
var car2=new Car();
这是最基本的方式,但是也存在和factory方式一样的毛病

3.prototype方式
function Car(){
}
Car.prototype.color="b";
Car.prototype.length=1;
Car.prototype.run=function(){alert("run");}
这个方式的缺点是,当这个类有一个引用属性时,改变一个对象的这个属性也会改变其他对象得属性
比如:
Car.prototype.data1=new Array();
var car1=new Car();
var car2=new Car();

car1.data1.push("a");
此时,car2.data也就包含了"a"元素

4.Prototype/Constructor杂合方式
function Car(){
  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方式

相关文章:

  • 2021-06-02
  • 2021-07-06
  • 2021-09-06
  • 2022-12-23
  • 2022-12-23
  • 2021-11-12
  • 2022-12-23
  • 2021-12-27
猜你喜欢
  • 2022-12-23
  • 2022-12-23
  • 2022-01-19
  • 2022-01-30
  • 2022-12-24
  • 2022-12-23
  • 2021-04-06
相关资源
相似解决方案