在JavaScript中,对象是拥有属性和方法的数据(可以与java中的对象类比)。
JavaScript自定义对象方式有以下7种:直接创建方式、对象初始化器方式、构造函数方法、prototype原型方式、混合的构造函数/原型方式、动态原型方式和工厂模式,这里叙述常用的5种:
备注:例子部分只展示函数体
一、直接创建式
语法结构
var 对象变量名 = new Object();
对象变量名. property1 = value1;
…;
对象变量名. propertyN = valueN;
对象变量名. methodName1 = function([参数列表]){
//函数体
}
…;
对象变量名. methodNameN = function([参数列表]){
//函数体
}
例子:
var student = new Object();
student.name="lulu";
student.study=function(){
console.log(this.name+"正学习");
}
student.study();//执行结果:lulu正在学习
二、对象初始化式
语法结构:
var 对象变量名 = {
property1 : value1,
property2 : value2,
…,
propertyN : valueN,
methodName1 : function([parameter_list]){
//函数体
},
…,
methodNameN : function([parameter_list]){
//函数体
}
}
例子:
var student = {
name: "lili",
study: function() {
console.log(this.name + "正在学习....");
}
}
student.study();//执行结果:lili正在学习
三、构造方法式
语法结构:
function 构造函数([参数列表]){
this.属性 = 属性值;
…
this.属性N = 属性值N;
this.函数1 = method1;
…
this.函数N = methodN;
}
function method1([参数列表]){
//函数体
}
…
function methodN([参数列表]){
//函数体
}
或者
function 构造函数([参数列表]){
this.属性 = 属性值;
…
this.属性N = 属性值N;
this.函数1 = function([参数列表]){
//函数体
} ;
…
this.函数N = function([参数列表]){
//函数体
} ;
}
例子:
function Student(name){
this.name=name;
this.study=function(){
console.log(this.name+"正在学习...");
}
}
var student = new Student("tim");
student.study();//执行结果:tim正在学习
四、prototype原型式
语法结构
function 对象构造器( ){
}
对象构造器.prototype.属性名=属性值;
对象构造器.prototype.函数名 = function([参数列表]){
//函数体
}
例子:
function Student(){
}
Student.prototype.name="tim";
Student.prototype.study=function(){
console.log(this.name+"正在学习...");
}
var student=new Student();
student.study();//执行结果:tim正在学习
五、混合(构造方法+原型)式
语法结构:
function 对象构造器([参数列表]){
}
对象构造器.prototype.函数名 = function([参数列表]){
//函数体
}
例子:
function Student(name){
this.name=name;
}
Student.prototype.study=function(){
console.log(this.name+"正在学习...");
}
var student = new Student("jim");
student.study();//执行结果:jim正在学习