Home  >  Article  >  Web Front-end  >  JavaScript 创建对象_json

JavaScript 创建对象_json

WBOY
WBOYOriginal
2016-05-16 18:50:00766browse

第一种:JSON方式/对象直接量
格式:
var 对象名 = {
变量1: 变量1的值,
变量1: 变量1的值,
……,
函数1: function() {
函数体
},
函数2: function() {
函数体
}//Note:最后的逗号要去除为了和IE兼容。
};
说明:
(1) 大括号内直接填写变量或者函数;
(2) 对象的内容与值以冒号分隔,成对出现;
(3) 包含的变量或者函数之间以逗号分隔;
(4) 函数需要写在function(){}的大括号之内。
例子:
var 对象名 = {
name: “Vicky”,
age: 26,
eat: function() {
alert(‘I wanna eat meat');
},
sleep: function() {
alert(‘I wanna sleep');
}
};
注释:类似的方式也叫做匿名类
匿名类举例:
{
index: '//',
reg: new RegExp('^//.*$'),
css: "comment"
}
上面的方式创建了类,只是没赋给一个变量而已。
第二种:function方式
格式:
function data() {
this.变量1=变量1的值;
this.变量2=变量2的值;
……;
this.函数1= function() {
函数体
};
this.函数2= function() {
函数体
};
}
说明:
(1) 其内的变量或者函数前必需写上this关键字;
(2) 对象的内容与值以等号分隔,成对出现;
(3) 包含的变量或者函数之间以分号分隔。
(4) 函数需要写在function(){}的大括号之内。
例子:
function data() {
this.name=“Vicky””;
this.age=26;
this.eat=function() {
alert(‘I wanna eat meat');
};
this.sleep=function() {
alert(‘I wanna sleep');
};
}
第三种:原型方式
格式:
var 对象名 = {};
对象名.prototype.变量1=变量1的值;
对象名.prototype.变量2=变量2的值;
……;
对象名.prototype.函数1= function() {
函数体
};
对象名.prototype.函数2= function() {
函数体
};
……;
说明:
(1) 初始对象体内可以不定义任何东西;
(2) 在要定义的变量前加“对象名.prototype.”的格式;
(3) 对象的内容与值以等号分隔,成对出现;
(4) 包含的变量或者函数之间以分号分隔,也可以省去分号。
(5) 函数需要写在function(){}的大括号之内。
例子:
var data = {};
data.prototype. name ="Vicky”;
data.prototype. age =20;
data.prototype. eat = function() {
alert(‘I wanna eat meat');
};
data.prototype. sleep= function() {
alert(‘I wanna sleep');
};
第四种:create方式
该方式利用了Prototype JavaScript组件库。
格式:
var 对象名 = Class.create();
Object.extend(对象名.prototype, {
变量1: 变量1的值,
变量1: 变量1的值,
……,
函数1: function() {
函数体
},
函数2: function() {
函数体
},
……
});
说明:
(1) 对象的创建使用了Prototype库中的Class.create()函数;
(2) 对象的内容使用Prototype库中的Object.extend()函数来扩展;
(3) 被扩展的对象在传入Object.extend函数时一定要带上prototype,
(4) 扩展内容被大括号包含,其内与JSON方式的定义格式完全相同。
例子:
var data = Class.create();
Object.extend(dta.prototype, {
name: "Vicky",
age: 20,
eat: function() {
alert(‘I wanna eat meat');
},
sleep: function() {
alert(‘I wanna sleep');
}
});
其实,JS对象的定义还有其它的方式,你也可以用上面4种进行组合定义,这显出了JS作为动态语言的自由性。
JS对象的创建正规方法如下:
var d1 = new Data();
JS对象变量的引用方式有两种:
(1) 点号方式引用,如,data.name。
(2) 数组方式引用,如,data[‘name']。

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn