【发布时间】:2011-05-08 00:20:26
【问题描述】:
围绕 JavaScript 函数参数的花括号有什么作用?
var port = chrome.extension.connect({name: "testing"});
port.postMessage({found: (count != undefined)});
【问题讨论】:
标签: javascript function arguments curly-braces
围绕 JavaScript 函数参数的花括号有什么作用?
var port = chrome.extension.connect({name: "testing"});
port.postMessage({found: (count != undefined)});
【问题讨论】:
标签: javascript function arguments curly-braces
自提出此问题以来,出现了第二个可能的答案。 Javascript ES6 引入了Destructuring Assignment。
var x = function({ foo }) {
console.log(foo)
}
var y = {
bar: "hello",
foo: "Good bye"
}
x(y)
Result: "Good bye"
【讨论】:
花括号表示一个对象字面量。这是一种发送数据键/值对的方式。
所以这个:
var obj = {name: "testing"};
这样用来访问数据。
obj.name; // gives you "testing"
你可以给对象几个逗号分隔的键/值对,只要键是唯一的。
var obj = {name: "testing",
another: "some other value",
"a-key": "needed quotes because of the hyphen"
};
您还可以使用方括号来访问对象的属性。
这在"a-key" 的情况下是必需的。
obj["a-key"] // gives you "needed quotes because of the hyphen"
使用方括号,您可以使用存储在变量中的属性名称访问值。
var some_variable = "name";
obj[ some_variable ] // gives you "testing"
【讨论】:
javascript 中的花括号用作创建对象的简写。例如:
// Create an object with a key "name" initialized to the value "testing"
var test = { name : "testing" };
alert(test.name); // alerts "testing"
查看 Douglas Crockford 的JavaScript Survey 了解更多详情。
【讨论】:
var x = {title: 'the title'};
定义一个具有属性的对象字面量。你可以做
x.title
这将评估为'标题;
这是将配置传递给方法的常用技术,这就是这里发生的事情。
【讨论】: