jQuery 中的extend() 是如何工作的?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4528744/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 17:24:36  来源:igfitidea点击:

How does extend() work in jQuery?

jqueryjquery-plugins

提问by Todd Terry

I saw this in a plugin:

我在插件中看到了这个:

var options = $.extend(defaults, options); 

How does it work?

它是如何工作的?

What does extend()do?

有什么作用extend()

回答by Craig Walker

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));

(The console.logfunction is intended to work in Firebug; replace it with alert() or some other output function if you like).

(该console.log函数旨在在 Firebug 中工作;如果您愿意,请将其替换为 alert() 或其他一些输出函数)。

The results are:

结果是:

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

By this we can see that jQuery.extend():

通过这个我们可以看到 jQuery.extend():

  • Starts with the object provided by the first parameter.
  • Adds to it any property in the second parameter. If the property already exists in the first parameter, it is overwritten. The object for the second parameter is unchanged.
  • Repeats the above with any subsequent parameter.
  • Returns the first parameter.
  • 从第一个参数提供的对象开始。
  • 将第二个参数中的任何属性添加到它。如果该属性已存在于第一个参数中,则它会被覆盖。第二个参数的对象不变。
  • 对任何后续参数重复上述操作。
  • 返回第一个参数。

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});

Note that "null" is a valid value for overwriting, but "undefined" isn't. You might be able to make use of this.

请注意,“null”是覆盖的有效值,但“undefined”不是。你或许可以利用这一点。

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);

Results in:

结果是:

A: Foo=null Bar=a

Single Parameter

单参数

If you pass just one object to jQuery.extend(), then jQuery assumes that the jQueryobject itselfis the "first" parameter (ie: the one to be modified), and your object is the "second" (ie: the one to add to the first). So:

如果您只将一个对象传递给jQuery.extend(),那么 jQuery 假定jQuery对象本身是“第一个”参数(即:要修改的参数),而您的对象是“第二个”(即:要添加到第一个参数的对象) . 所以:

console.log( "Before: " + jQuery.foo );
jQuery.extend({foo:1});
console.log( "After: " + jQuery.foo );

Results in:

结果是:

Before: undefined
After: 1

回答by Gopal

It merges the content of one object to another. If we pass two objects, second object properties are added to the first object / first parameter

它将一个对象的内容合并到另一个对象。如果我们传递两个对象,则将第二个对象属性添加到第一个对象/第一个参数

Ex: $.extend(object1, object2);

Now object1 contains properties of object2

现在object1 包含 object2 的属性

If we want to merge two objects, then we need to pass empty object in the first parameter

如果我们想合并两个对象,那么我们需要在第一个参数中传递空对象

Ex: var newObject = $.extend({}, object1, object2);

Now newObject contains both properties of object1 and object2.

现在newObject 包含 object1 和 object2 的两个属性

回答by JOBG

From jQuery Documentation

来自 jQuery 文档

Merge the contents of two or more objects together into the first object.

将两个或多个对象的内容合并到第一个对象中。

In a plugin context:If the user does not set the optional parameters for the function, then a default value will be used instead.

在插件上下文中:如果用户没有为函数设置可选参数,则将使用默认值。

回答by christian Nguyen

How does extend() work in jQuery? [Resolved]

jQuery 中的extend() 是如何工作的?[解决]

jQuery have deep copy and light copy. The first boolean decide it, true for deep and false for light.

jQuery 有深拷贝和轻拷贝。第一个布尔值决定它,为深为真,为浅为假。

For example:

例如:

  • jQuery.extend(false, {'a' : {'a1': 1}}, {'a': {'a2': 2}})

    the result will be: {'a': {'a2': 2}} because this is light copy just compare level 1.

    enter image description here

  • jQuery.extend(true, {'a' : {'a1': 1}}, {'a': {'a2': 2}})

    the result will be: {'a': {'a1': 1, 'a2': 2}} This is deep copy with many level of object (just like level of array)

    enter image description here

  • jQuery.extend(a,b,c) with a, b, c is object or array. The flow overrite will be b->a, c ->a (b overrite a, c override a ...) this function will return a and a also change value too.

  • jQuery.extend(false, {'a': {'a1': 1}}, {'a': {'a2': 2}})

    结果将是:{'a': {'a2': 2}} 因为这是轻量级副本,只需比较级别 1。

    在此处输入图片说明

  • jQuery.extend(true, {'a' : {'a1': 1}}, {'a': {'a2': 2}})

    结果将是: {'a': {'a1': 1, 'a2': 2}} 这是具有多个对象级别的深拷贝(就像数组级别)

    在此处输入图片说明

  • jQuery.extend(a,b,c) 与 a, b, c 是对象或数组。流覆盖将是 b->a, c ->a (b overrite a, c override a ...) 这个函数将返回 a 并且 a 也会改变值。

Advanced Examples:

高级示例:

  • jQuery.extend({'number_param': 1})

    In case you just pass one param. jQuery will extend itself. console.log(jQuery['number_param']) will output 1.

    enter image description here

  • jQuery.extend(1, {'number_param': '2'}); This example is not append jQuery itself. The first parameter must be boolean. In this case it will return {'number_param': '2'} and jQuery not get updated.

    enter image description here

  • jQuery.extend(a, b, c, d ,e , f); The order merge will be . b ->a , c -> a, d -> a, e -> a, f ->a (b override a, c override a ...) . And result return will be a.

    with a= {'p': 1}. jQuery.extend(a, {'p': 2},{'p': 3},{'p': 4},{'p': 5}) will return a, and a = {'p': 6}. The number parameters pass to this function is unlimited.

    enter image description here

  • jQuery.extend({'number_param': 1})

    如果您只传递一个参数。jQuery 将扩展自身。console.log(jQuery['number_param']) 将输出 1。

    在此处输入图片说明

  • jQuery.extend(1, {'number_param': '2'}); 这个例子不是附加 jQuery 本身。第一个参数必须是布尔值。在这种情况下,它将返回 {'number_param': '2'} 并且 jQuery 不会更新。

    在此处输入图片说明

  • jQuery.extend(a, b, c, d,e, f); 订单合并将是 。b ->a , c -> a, d -> a, e -> a, f ->a (b override a, c override a ...) 。结果返回将是一个。

    与 a= {'p': 1}。jQuery.extend(a, {'p': 2},{'p': 3},{'p': 4},{'p': 5}) 将返回 a,并且 a = {'p': 6}。传递给这个函数的参数数量是无限的。

    在此处输入图片说明

回答by Sanjay Bharwani

The purpose is to extend an existing object. For e.g. if we have a template object and we want to extend that by adding more properties or override existing properties, jquery extend can be useful.

目的是扩展现有对象。例如,如果我们有一个模板对象并且我们想通过添加更多属性或覆盖现有属性来扩展它,jquery 扩展可能很有用。

var carObjectTemplate = {
"make": "honda",
"model":"city",
"mileage":"20",
"variant":"petrol"

};

};

now if we want to extend it, $.extend(true, {"color":"red"}, carObjectTemplate, {"model": 'amaze'});it will give us ouput, extending carObjectTemplate and adding

现在如果我们想扩展它, $.extend(true, {"color":"red"}, carObjectTemplate, {"model": 'amaze'});它会给我们输出,扩展 carObjectTemplate 并添加

{"color":"red"} property and overriding "model" property from "city" to "amaze"

first boolean parameter true/false is to indicate if we need a deep or shallow copy

第一个布尔参数 true/false 表示我们需要深拷贝还是浅拷贝

回答by Gabriele Petrioli

It does exactly this

它正是这样做的

Description: Merge the contents of two or more objects together into the first object.

描述:将两个或多个对象的内容合并到第一个对象中。

More at jQuery.extend()

更多在jQuery.extend()