본문 바로가기
📌 Front End/└ jQuery

[jQuery] $.fn.extend({ }) vs $.extend({ }) 비교하기

by 쫄리_ 2023. 3. 10.
728x90
반응형

객체 형식  ▶  { , }


 

$.fn.extend({ })

메서드 확장 정의

jQuery 를 확장 즉 커스터마이징

jQuery 의 기본 함수에 추가하는 내가 쓰고자 하는 함수를 넣어서 확장

.fn -> 아직 정해지지 않은 자바스크립트에서 지원하는 오브젝트 전체를 뜻하는 가명

         .fn 으로 생성된 메소드는 아무나 이용하고 접근할 수 있는 메소드가 된다.

jquery prototype(원본의) property 확장.

$.fn.extend() 의 경우 jquery prototype의 prototype을 확장한다는 의미로

 $.fn.extend({
          method1 : function(){}
    })

와 같이 선언한다.
다른 jquery method들 처럼 $("div").method1(); 로 호출해서 사용한다.

jquery prototype에 추가한 property 는 "this" 를 통해서 DOM Element 에 접근이 가능하다.

$.fn.extend({
          toogleActivateStatue : function(){
               var $this = $(this);
               $this.css("color","white");
          },
         toogleDisActivateStatue : function(){
               var $this = $(this);
               $this.css("color","black");
        }
    });

    $("#itemStateToggle").click(function(){
         var i = Math.floor((Math.random() * 3 ) );
         console.log(i);

         $(".toolbar-item").each(function(index){
                if(index == i){
                      $(this).toogleActivateStatue();
                }else{
                       $(this).toogleDisActivateStatue();
                }
         });
    });

 

$.extend({ })

객체(오브젝트) 확장 정의

Object 들의 merge!

.extend -> 합치는 메서드

왜 앞에 아무것도 없냐고? .fn과 마찬가지로 jquery가 자체 지원하는 선택자 없는 메소드 또는 가짜 가상의 선택자(jquery)를 사용하기 때문

$.extend({ // 제이쿼리 객체정의

       bizServiceCall: function ( ) {}       // bizServiceCall 메서드명!!

)}

*{background-color: #ff0000;}.extend 구조%*%

$.extend({참/거짓}, 오브젝트1, 오브젝트2);
참거짓부분은 합치는 방법에 대해 설정하는 것
오직 true만 쓸 수 있고, 아무것도 쓰지 않으면 거짓(false)를 전달하게 된다.
이건 겹칠때 덮어씌울것인가,, 덮어씌우지 않을 것인가에 대한 결정이다.
true이면 덮어씌우지 않고, false이면 덮어씌운다.

$.extend({참/거짓}, 오브젝트1, 오브젝트2);
오브젝트1에 오브젝트2를 덮어씌운다.
merge 오브젝트2 into 오브젝트1 이라고 보면됨 (오브젝트2를 오브젝트1에 합친다.)

 

$.extend({}) : Object 들의 merge!

 $.extend({
          method1 : function(){}
    });

로 선언한 경우 $.method1(); 로 호출해서 사용한다.
이와 같이 선언된 경우 this를 사용하여 DOM Element에 접근할 수 없다.

보통의 jquery method 처럼 $("#id")와 같은 selector가 필요 없으며
$.ajax() 처럼 사용하면 된다.
주로 method들을 선언하는 것보다는 object들을 합치기 위해 사용하는 경우가 많다.

var Person = function(name){
          this.name = name;
    };

    var speaker = {
          speak : function(){
                return this.name + " is speaking";
          }
    };

    var mover= {
          walk : function(){
                return this.name + " is walking";
          },
          run : function(){
                return this.name + " is running";
          }
    };

    $.extend(Person.prototype, speaker, mover);
    //Person.prototype에 speaker과 mover를 merge 시킨다.

    var john = new Person("john");
    console.log(john.walk()); 
    //"john is walking" 
 

$.extend(obj1, obj2);

=> obj2의 값을 odj1에 합친다.
=> obj1 key와 obj2의 key 값이 겹치는 경우 obj2의 key 값에 해당하는 내용으로 덮어쓰기 실행

var object1 = {
          apple: 0,
          banana: { weight: 52, price: 100 },
          cherry: 97
    };
    var object2 = {
          banana: { price: 200 },
          durian: 100
    };

    // Merge object2 into object1
    $.extend( object1, object2 );

    //{"apple":0,"banana":{"price":200},"cherry":97,"durian":100}
 

$.extend(true, obj1, obj2);

=> obj2의 값을 obj1에 합친다.
=> key 값이 겹치는 부분의 값만 덮어쓰기 실행

var object1 = {
          apple: 0,
          banana: { weight: 52, price: 100 },
          cherry: 97
    };
    var object2 = {
          banana: { price: 200 },
          durian: 100
    };

    // Merge object2 into object1, recursively
    $.extend(true, object1, object2 );

    //object 1 : {"apple":0,"banana":{"weight":52,"price":200},"cherry":97,"durian":100}
 

$.extend({}, obj1, obj2);

=> obj1을 변경하지 않고 obj2와 obj1을 합치게 시킨다.

 var defaults = { validate: false, limit: 5, name: "foo" };
    var options = { validate: true, name: "bar" };

    // Merge defaults and options, without modifying defaults
    var settings = $.extend( {}, defaults, options );

    defaults -- {"validate":false,"limit":5,"name":"foo"}
    options -- {"validate":true,"name":"bar"}
    settings -- {"validate":true,"limit":5,"name":"bar"}

 

728x90
반응형