extend()在jQuery中如何工作? [英] How does extend() work in jQuery?
问题描述
我在插件中看到了这一点
I saw this in a plugin:
var options = $.extend(defaults, options);
它如何工作?
extend()
的作用是什么?
推荐答案
多个参数
该文档不能准确解释扩展的工作原理,因此我进行了一些测试:
Multiple Parameters
The documentation isn't precise in explaining how extend works, so I ran a little test:
var a = {foo: 1, bar: 1};
var b = {foo: 2, baz: 2};
var c = {foo: 3};
var r = jQuery.extend(a,b,c);
console.log("A: Foo=" + a.foo + " Bar=" + a.bar + " Baz=" + a.baz);
console.log("B: Foo=" + b.foo + " Bar=" + b.bar + " Baz=" + b.baz);
console.log("C: Foo=" + c.foo + " Bar=" + c.bar + " Baz=" + c.baz);
console.log("R: Foo=" + r.foo + " Bar=" + r.bar + " Baz=" + r.baz);
console.log("A === R?: " + (a === r));
(console.log
函数旨在在Firebug中工作;如果需要,可以将其替换为alert()或其他一些输出函数).
(The console.log
function is intended to work in Firebug; replace it with alert() or some other output function if you like).
结果是:
A: Foo=3 Bar=1 Baz=2
B: Foo=2 Bar=undefined Baz=2
C: Foo=3 Bar=undefined Baz=undefined
R: Foo=3 Bar=1 Baz=2
A === R?: true
通过这个,我们可以看到jQuery.extend():
By this we can see that jQuery.extend():
- 从第一个参数提供的对象开始.
- 在第二个参数中添加任何属性.如果该属性已经存在于第一个参数中,则它将被覆盖.第二个参数的对象不变.
- 使用任何后续参数重复上述操作.
- 返回第一个参数.
这对于将用户和默认选项对象组合在一起以获得完整的选项集很有用:
This is useful for combining user and default option-objects together to get a complete set of options:
function foo(userOptions) {
var defaultOptions = {
foo: 2,
bar: 2
};
var someOtherDefaultOptions = {
baz: 3
};
var allOptions = jQuery.extend(
defaultOptions,
someOtherDefaultOptions,
userOptions
);
doSomething(allOptions);
}
foo({foo:1, baz:1});
请注意,"null"是用于覆盖的有效值,但"undefined"不是有效值.您也许可以利用它.
Note that "null" is a valid value for overwriting, but "undefined" isn't. You might be able to make use of this.
var a = {foo: "a", bar: "a"};
var b = {foo: null, bar: undefined};
jQuery.extend(a,b);
console.log("A: Foo=" + a.foo + " Bar=" + a.bar);
结果:
A: Foo=null Bar=a
单个参数
如果仅将一个对象传递给jQuery.extend()
,则jQuery假定jQuery
对象本身是第一个"参数(即:要修改的参数),而您的对象是第二个"(即:添加到第一个的那个).所以:
Single Parameter
If you pass just one object to jQuery.extend()
, then jQuery assumes that the jQuery
object itself is the "first" parameter (ie: the one to be modified), and your object is the "second" (ie: the one to add to the first). So:
console.log( "Before: " + jQuery.foo );
jQuery.extend({foo:1});
console.log( "After: " + jQuery.foo );
结果:
Before: undefined
After: 1
这篇关于extend()在jQuery中如何工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!