在javascript中返回花括号的含义是什么(例如return {init:init}) [英] What do returning curly braces mean in javascript (ex. return { init : init} )
问题描述
我正在查看此代码:
$(function(){
var $sidescroll = (function() {
init = function() {
//STUFF
};
return { init : init }; //What does this do?
})();
$sidescroll.init();
});
return语句是什么意思?我以前没有在return语句中看过大括号,甚至不确定'init:init'是什么。
What does the return statement mean? I haven't seen curly braces in a return statement before, and am not even sure what 'init : init' does.
推荐答案
curly括号在javascript中表示两件事:
Curly braces mean two things in javascript:
- blocks
- object literals
您可能已经看过第二个 - 在其他语言中也称为词典,键值对,关联数组等:
You've probably seen the second -- also known in other languages as "dictionaries", key-value pairs, associative arrays, etc:
myDict = { a: "apple", b: "banana" };
当我们说
return { a: "apple" };
与说法相同
myDict = { a: "apple" };
return myDict;
在这种情况下令人困惑的事情是(1)键和值相同/具有相同的字符表示,(2)该值不是普通的字符串或变量,而是一个函数。也就是说,访问对象/字典的键init将为您提供一个可以使用()
调用的函数。
The "confusing" thing in this case is that (1) the key and the value are identical/have the same character representation, and (2) the value is not a normal string or variable but, a function. That is, accessing the key "init" of your object/dictionary will give you a function that you can call with ()
.
这篇关于在javascript中返回花括号的含义是什么(例如return {init:init})的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!