How does the extend() function work in jQuery?

前端 未结 6 1764
时光取名叫无心
时光取名叫无心 2020-12-12 11:04

I saw this in a plugin:

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

How does it work?

What does extend() do?

6条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-12 11:21

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

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

    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.

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

    • 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.

    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.

    • 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.

    • 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.

提交回复
热议问题