jQuery 中的 extend() 函数是如何工作的? [英] How does the extend() function work in jQuery?
问题描述
我在插件中看到了这个:
I saw this in a plugin:
var options = $.extend(defaults, options);
它是如何工作的?
extend()
有什么作用?
What does extend()
do?
推荐答案
多参数
文档没有准确解释扩展的工作原理,所以我进行了一些测试:
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
对象 itself 是第一个"参数(即:要修改的那个),您的对象是第二个"(即:要添加到第一个的那个).所以:
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
这篇关于jQuery 中的 extend() 函数是如何工作的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!