对象的声明方式有多种,那么我们看一下有哪几种吧!
1、字面量的方式声明对象:
var obj = {
属性名称:属性值,
方法名称:function (){
//函数执行体
}
}
2、new 操作符+Object 声明对象:
var obj = new Object();
obj.属性名称 = 属性值;
obj.方法名称 = function (){
//函数执行体
}
3、构造函数声明对象:
function text([参数列表]){
this.属性名称 = 属性值;
this.方法名称 = function (){
//函数执行体
}
}
var obj = new text(参数);
4、工厂方式声明对象:
function text(name, age){
var obj = new Object();
obj.name = name;
obj.age = age;
obj.run = function (){
return this.name + this.age; // 要return
}
}
var obj1 = text('zhaoweinian', 21);
var obj2 = text('lisi', 30);
5、原型模式声明对象:
function text(name, age){
text.prototype.属性名称 = 属性值;
text.prototype.方法名称 = function (){
//函数执行体
}
}
var obj = new text('lisi', 20);
6、混合模式声明对象:
function text(name, age){
this.name = name;
this.age = age;
}
text.prototype.属性名称 = 属性值;
text.prototype.方法名称 = function (){
//函数执行体
}
var obj = new text('zhangsan', 30);