我们为什么要用({ })
?
它是代表吗?
使用这种语法意味着什么?
What are we wrapping with it?
例如:
$.ajaxSetup ({ // <-- THIS
error: fError,
compelete: fComp,
success: fSucc
}); // <-- AND THIS
我们为什么要用({ })
?
它是代表吗?
使用这种语法意味着什么?
What are we wrapping with it?
例如:
$.ajaxSetup ({ // <-- THIS
error: fError,
compelete: fComp,
success: fSucc
}); // <-- AND THIS
{}
is object notation in JavaScript. For example:
$('selector').plugin({ option1: 'value' });
In this case you're passing an object containing your settings to the plugin. The plugin can deal with this as a object, whatever it's referenced as, for example:
settings.option1 //the option you passed in.
当然,它有更多的用途,但这是jQuery中最常见的示例..animate()
、$.ajax()
、.css()
等函数也是如此.任何接受属性的函数通常都使用此格式.
根据要求,还可以举几个例子:
传递的对象内的任何对象也可以是函数,而不仅仅是属性,例如:
$("<input>", {
type: "text",
focusin: function() { alert("Hi, you focused me!"); }
});
这会将该输入的焦点事件设置为具有alert .另一种方法是扩展对象,向其添加属性,如下所示:
var person = { first_name: "John" };
$.extend(person, { last_name: "Smith" });
//equivalent to:
person.last_name = "Smith";
//or:
person["last_name"] = "Smith";
Now person
has the last_name
property. This is often used by plugins as well, to take the default settings, then merge any settings you passed in, overwriting with any settings you specified, using defaults for the rest.
Why are we using it? Well...that's how JavaScript works, and in the jQuery spirit: it's an extremely terse and flexible way to pass information.