extend ()는 jQuery에서 어떻게 작동합니까?
나는 이것을 플러그인에서 보았다.
var options = $.extend(defaults, options);
어떻게 작동합니까?
무엇을 extend()
합니까?
여러 매개 변수
문서는 extend가 어떻게 작동하는지 설명하는 데 정확하지 않으므로 약간의 테스트를 실행했습니다.
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 () 또는 다른 출력 함수로 대체하십시오).
결과는 다음과 같습니다.
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 ()를 볼 수 있습니다 :
- 첫 번째 매개 변수에서 제공하는 객체로 시작합니다.
- 두 번째 매개 변수의 속성을 추가합니다. 속성이 이미 첫 번째 매개 변수에있는 경우 덮어 씁니다. 두 번째 매개 변수의 개체는 변경되지 않습니다.
- 후속 매개 변수로 위의 과정을 반복합니다.
- 첫 번째 매개 변수를 반환합니다.
이것은 완전한 옵션 세트를 얻기 위해 사용자 및 기본 옵션 오브젝트를 함께 결합하는 데 유용합니다.
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"는 그렇지 않습니다. 이것을 사용할 수 있습니다.
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
객체 자체 가 "첫 번째"매개 변수 (예 : 수정할 매개 변수)이고 객체가 "두 번째"(예 : 첫 번째 매개 변수에 추가 할 매개 변수)라고 가정합니다 . . 그래서:
console.log( "Before: " + jQuery.foo );
jQuery.extend({foo:1});
console.log( "After: " + jQuery.foo );
결과 :
Before: undefined
After: 1
그것은 또 다른 하나의 객체의 내용을 병합합니다 . 두 개체를 전달하면 두 번째 개체 속성이 첫 번째 개체 / 첫 번째 매개 변수에 추가됩니다.
Ex: $.extend(object1, object2);
이제 object1에는 object2의 속성이 포함됩니다.
두 객체 를 병합 하려면 첫 번째 매개 변수에 빈 객체를 전달해야합니다.
Ex: var newObject = $.extend({}, object1, object2);
Now newObject contains both properties of object1 and object2.
From jQuery Documentation
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.
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.
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.
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
{"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
It does exactly this
Description: Merge the contents of two or more objects together into the first object.
More at jQuery.extend()
참고URL : https://stackoverflow.com/questions/4528744/how-does-extend-work-in-jquery
'developer tip' 카테고리의 다른 글
maven 빌드 실패 : Javac 컴파일러를 찾을 수 없음 : jre 또는 jdk 문제 (0) | 2020.08.07 |
---|---|
파이썬 문자열에서 정규식 특수 문자를 이스케이프 처리 (0) | 2020.08.07 |
iframe이 위험하고 보안 위험으로 간주되는 이유는 무엇입니까? (0) | 2020.08.07 |
SSL을 사용하는 html5 Websocket (0) | 2020.08.07 |
pow (a, d, n)이 a ** d % n보다 훨씬 빠른 이유는 무엇입니까? (0) | 2020.08.07 |