创建类
来源:互联网 发布:老干部,老司机网络意思 编辑:程序博客网 时间:2024/06/06 20:09
JS中创建类的方法
(2009-11-05 08:37:05)
转载
标签:
杂谈
分类:jscript学习笔记javascript的class建立是个有意思的话题, 确切的说, OO的javascript就是比较有趣的,因为javascript并没有在设计的时候定位为OO. 下面的文章是转的别人的, 集中于话题"javascript语言中的Class的创建"
在Javascript中构建一个类有好几种方法:
1.Factory 方式
重新创建一次.浪费内存
2.Constructor方式
3.prototype方式
比如:
4.Prototype/Constructor杂合方式
5.动态prototype方式
在Javascript中构建一个类有好几种方法:
1.Factory 方式
function createCar(){
varcar = newObject();
car.color="b";
car.length=1;
car.run=function(){alert("run");}
return car;
}
定义这么一个函数之后,就可以用:
varcar1 = createCar();
varcar2 = createCar();
来创建新的对象,这种方式的问题是每一次创建一个car对象,run Function也都必须varcar = newObject();
car.color="b";
car.length=1;
car.run=function(){alert("run");}
return car;
}
定义这么一个函数之后,就可以用:
varcar1 = createCar();
varcar2 = createCar();
重新创建一次.浪费内存
2.Constructor方式
function Car(){
this.color="b";
this.length=1;
this.run=function(){alert("run");}
}
var car1=new Car();
var car2=new Car();
这是最基本的方式,但是也存在和factory方式一样的毛病this.color="b";
this.length=1;
this.run=function(){alert("run");}
}
var car1=new Car();
var car2=new Car();
3.prototype方式
function Car(){
}
Car.prototype.color="b";
Car.prototype.length=1;
Car.prototype.run=function(){alert("run");}
这个方式的缺点是,当这个类有一个引用属性时,改变一个对象的这个属性也会改变其他对象得属性}
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"元素var car1=new Car();
var car2=new Car();
car1.data1.push("a");
4.Prototype/Constructor杂合方式
function Car(){
this.color="b";
this.length=1;
this.data1=new Array();
}
Car.prototype.run=function(){
alert("dddd");
}
这种方式去除了那些缺点.是目前比较大范围使用的方式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(typeofCar.initilize=="undefined"){
Car.prototype.run=function(){alert("a");}
}
Car.initilize=true;
}
这几种方式中,最常用的是杂合prototype/constructor 和 动态prototype方式this.color="b";
this.length=1;
this.data1=new Array();
if(typeofCar.initilize=="undefined"){
Car.prototype.run=function(){alert("a");}
}
Car.initilize=true;
}
- 创建类
- 创建类
- 创建类!
- 创建类
- 创建类
- 创建FileGeodatabase,创建要素类,创建域对象,创建子类,创建要素
- 文件创建辅助类
- 用类创建常量
- 创建一个CTabView类
- 3、创建类
- 创建Session类
- c#创建文件夹类
- file类创建目录
- 创建二级联动类
- AJAX创建类
- Web 程序创建类
- 创建要素类
- 根据字符串创建类
- GL追溯子模块的视图
- 论文
- 请慎用java的File#renameTo(File)方法
- js创建类
- JSR规范
- 创建类
- 桶排序及其应用
- SQL获取所有数据库名、表名、储存过程以及参数列表
- 中联绿盟面试
- SQL中CAST和CONVERT的区别是什么?
- 共享资源的公平性研究
- 动态改变表单的action.
- const成员函数的使用
- sql语句学习笔记(5)-sql语法