JavaScript语法

6

我经常发现一些看起来像下面例子的JavaScript代码。有人能解释一下吗?因为我以前没有见过这样写JavaScript的。

“SomethingHere”和冒号代表什么?我习惯于看到“function myFunction()”,但不是下面所示的那样。

 SomethingHere: function () {

              There is code here that I understand.
         }
5个回答

7

这是对象字面量表示法。它是一种使用以下形式声明对象的方法:

{
    propertyName: value
}

例如,有这样一个例子:
var obj = {
    fruit: "apple",
    id: 123,
    sayHello: function() { return "Hi"; }
};
alert(obj.fruit);
alert(obj.id);
alert(obj.sayHello());

1
更准确地说:对象字面量表示法。 - Jason S
1
另外,你的 alert(obj.sayHello()) 是不正确的,因为 sayHello 本身使用了 alert()。 - Jason S
当然。如果出现这种情况,请毫不犹豫地编辑帖子。 - Alex Turpin
好的--我倾向于避免编辑别人的答案,因为这几乎总是显得过于强势。 - Jason S
我想这取决于人。如果你再次遇到我的帖子,随意编辑 :) - Alex Turpin

2
你可以像这样在Javascript中创建一个对象:
var obj = {
 a: 1,
 b: 2
};

您还可以拥有作为函数的属性:

var obj = {
 SomethingHere: function() { alert("hello"); },
 b: 2
};

2

基本上,在这个范围/语法中,你必须有命名参数,这是将函数放入对象的方法。


1

正如其他答案所指出的那样,这是对象字面量表示法的一个例子。可以像这样声明一个对象:

var myObj = new Object();

然而,它也可以使用对象字面符号表示法声明,像这样:

var myObj = { };

当使用对象字面量语法时,可以立即在打开和关闭大括号内使用namevalue语法添加方法和属性。例如:

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

在这种情况下,“SomethingHere”是一个“方法”,意味着它是对象的成员函数。它的重要性在于特殊变量this。在以下两个函数定义中,this指的是浏览器窗口变量(假设您正在浏览器中运行代码):
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*/
}

在这个例子中,this 指的是封闭对象 myObj。
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 */
    }
};

0

编辑:不要提到JSON,因为它可能会被误解为数据格式。

这是JavaScript对象表示法。你可以创建一个函数,例如:


var SomethingHere = function() {
};

或者...


var Singleton = {
   SomethingHere: function()
   {
    ...
   }
}


5
那实际上不是 JSON。它只是一个 JavaScript 对象。JSON 是基于 JavaScript 对象的数据格式,但其语法要求更加严格。例如,键名必须用引号括起来。在这里可以了解更多信息:http://json.org/ - Matthew Manela
3
这不是JSON。JSON是一种基于JavaScript语法的数据格式,用于对象字面量、数组字面量和其他各种基本数据类型。它不包括函数。 - Quentin
1
底线是,“SomethingHere”是一个被定义为函数的变量。你可以使用“=”在JavaScript对象之外定义一个函数,或者使用“:”将其作为对象的属性。 - Adrian J. Moreno
1
@Chris,谢谢!我已经阅读了,当然,你是对的,它并不是技术上的JSON。 - Joel A. Villarreal Bertoldi
1
如果你想要更准确地表达,你可以提到它是对象字面量表示法,而不是使用构造函数/实例/原型对象:http://www.davidpirek.com/blog.aspx?n=JavaScript-Class-Constructor-vs.-Object-Literal:-Difference-in-Implementation-and-Inheritance 享受阅读 :) - Chris Baker
显示剩余5条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接