2013-03-23 3 views
3

처음에 내 자신의 코드를 작성하기 시작한 후에 jQuery의 '향상된'init 생성자를 나중에 이해할 때까지는 다른 방법으로 객체를 구성해야했습니다. 내 옛날 방식을 유지해야하는지 아니면 내 자신의 '향상된'init 생성자를 사용해야하는지 궁금합니다.더 좋은 초기화 형태는 무엇입니까?


내 생성자 :

var $ = function(selector,context,createObj) { 
     if(createObj) { 
      // actually initiating object 
     } else { 
      return new $(selector,context,true); 
     } 
}; 

jQuery를 :

jQuery = function(selector, context) { 
    // The jQuery object is actually just the init constructor 'enhanced' 
    return new jQuery.fn.init(selector, context, rootjQuery); 
}; 

실제 초기화 :

init: function(selector, context, rootjQuery) { 
    // some code 
} 

변경 프로토 타입 (jQuery.prototype.init.prototype = jQuery.prototype) :

jQuery.fn.init.prototype = jQuery.fn; 
+1

대체 방법을 보여줄 수 있으면 멋지게 될 것입니다. – JJJ

+0

jQuery의 생성자가 추가되었습니다. – FrameDev

답변

2

jQuery's constructor pattern 역사적 성장과 나쁜 관행입니다 - 또는 적어도 불필요하게 복잡합니다. new (잘못된 경우)을 사용하지 않고 잘 작동하는 생성자를 사용하려면

function $(selector, context) { 
    if (this instanceof $) { 
     // actually initiating object 
    } else { 
     return new $(selector, context); 
    } 
} 
+0

** [my code] ** (http://stackoverflow.com/questions/23184344/javascripts-super-constructor-clarification)과 유사하게 3 행에서 메소드 추가를 시작합니다. 코드? 'if (this instanceof $) {this.foo = function() {...} ...}'? –

+0

예, 정확하게. 아니면 조기 리턴을하고 평범한 생성자 앞에'if (! (this instanceof $))가 새로운 $ (...);를 반환합니다. – Bergi

관련 문제