我经常发现一些看起来像下面例子的JavaScript代码。有人能解释一下吗?因为我以前没有见过这样写JavaScript的。
“SomethingHere”和冒号代表什么?我习惯于看到“function myFunction()”,但不是下面所示的那样。
SomethingHere: function () {
There is code here that I understand.
}
我经常发现一些看起来像下面例子的JavaScript代码。有人能解释一下吗?因为我以前没有见过这样写JavaScript的。
“SomethingHere”和冒号代表什么?我习惯于看到“function myFunction()”,但不是下面所示的那样。
SomethingHere: function () {
There is code here that I understand.
}
这是对象字面量表示法。它是一种使用以下形式声明对象的方法:
{
propertyName: value
}
var obj = {
fruit: "apple",
id: 123,
sayHello: function() { return "Hi"; }
};
alert(obj.fruit);
alert(obj.id);
alert(obj.sayHello());
var obj = {
a: 1,
b: 2
};
您还可以拥有作为函数的属性:
var obj = {
SomethingHere: function() { alert("hello"); },
b: 2
};
基本上,在这个范围/语法中,你必须有命名参数,这是将函数放入对象的方法。
正如其他答案所指出的那样,这是对象字面量表示法的一个例子。可以像这样声明一个对象:
var myObj = new Object();
然而,它也可以使用对象字面符号表示法声明,像这样:
var myObj = { };
当使用对象字面量语法时,可以立即在打开和关闭大括号内使用name:value语法添加方法和属性。例如:
var myObj = {
name: 'Dave',
id: 42,
SomethingHere: function() {
/* function body */
}
};
alert(myObj.name); // Displays Dave
alert(myObj.id); // Displays 42
myObj.SomethingHere(); // Executes method SomethingHere
function foo() {
/* this.document refers to window.document */
/* this.location refers to window.location*/
}
var bar = function() {
/* Same as above, just a different syntax for declaring the function.
/* this.document refers to window.document */
/* this.location refers to window.location*/
}
var myObj = {
name = 'Dave',
id = 42,
myMethod: function() {
/* this.name refers to the name property of myObj, i.e., 'Dave' */
/* this.id refers to the id property of myObj, i.e., 42 */
/* this.location is undefined */
/* this.document is undefined */
}
};
编辑:不要提到JSON,因为它可能会被误解为数据格式。
这是JavaScript对象表示法。你可以创建一个函数,例如:
var SomethingHere = function() {
};
或者...
var Singleton = {
SomethingHere: function()
{
...
}
}
alert(obj.sayHello())
是不正确的,因为 sayHello 本身使用了 alert()。 - Jason S