2016-07-08 2 views
0

jQuery 플러그인을 작성한 경험이 거의없고 JavaScript 디자인 패턴을 사용한 경험이 거의 없으므로 부담하십시오.jQuery 객체 리터럴 메서드 확장/재정의 - 범위 외 문제

필자가 작성한 jQuery 확장에서 싱글 톤 패턴을 사용하고 있습니다. 그게 잘 작동하지만, 내 싱글 톤 객체의 메서드와 속성을 확장/재정의 할 수 있기를 원합니다.

이 작업을 수행하려면 런타임에 속성 개체 리터럴과 메서드 개체 리터럴을 포함하는 var self = {} 마스터 개체가 있어야합니다. 각각의 객체 리터럴의 개별 속성과 메서드는 전달되거나 기본값으로 설정됩니다.

self.properties 또는 self.methods에 액세스하려는 메서드를 전달할 때까지 작동합니다. self은 싱글 톤 객체에서만 정의되며 전달할 객체 리터럴이 아니기 때문에 아무 것도 전달되기 전에 JavaScript 오류가 발생합니다.

이 점을 더 잘 이해하기 위해 아래에 제가 수행하려는 작업과 매우 흡사 한 예제를 작성했습니다.

;(function ($, window, document, undefined) { 
    $.extend({ 
     MyObject : function(options) { 

      // enfore singleton pattern 
      $.MyObject = function() { 
       if(typeof $.MyObject != 'undefined') { // if an instance exists 
        console.log('$.MyObject is a singleton - original instance returned'); 
        return $.MyObject; // return original instance 
       } 
       else return this; // else, return this instance 
      }; 

      var self = {}, 
      defaults = { 
       properties : { 
        prop : true, 
        foo : "bar" 
       }, 
       methods : { 
        main : function() { 
         console.log(self.properties.foo); // console logs "bar" 
        } 
       } 
      }; 

      this.init = function(options) { 
       self = $.extend({}, defaults, options); // set properties to defaults unless options were provided 
       self.methods.main(); 
      }; 

      this.init(options); 

      return this; 
     } 

    }); 

})(jQuery, window, document); 

$(window).load(function() { 
    $.MyObject({ 
     properties : { 
      foo : "baz" 
     }, 
     methods : { 
      main : function() { 
       if(self.properties.prop) { // Uncaught TypeError: Cannot read property 'prop' of undefined 
        console.log(self.properties.foo); // Uncaught TypeError: Cannot read property 'foo' of undefined 
       } 
      } 
     } 
    }); 
}); 

나는 내가하는 일을 과도하게 복잡하게 만들었습니다. 이 시점에서, 나는 아마 이것을 할 더 좋은 방법이 있다고 생각하고 있습니다.

의견이 있으십니까?

답변

1

당신은 init()에서 깊은 확장을 원할 것입니다. main()에서 call()을 통해 현재 옵션을 "this"로 전달할 수도 있습니다.

+0

아 남자

;(function ($, window, document, undefined) { $.extend({ MyObject : function(options) { // --------------- // enforce singleton pattern // --------------- $.MyObject = function() { if (typeof $.MyObject === 'undefined') { return this; } console.log('$.MyObject is a singleton...'); return $.MyObject; }; // --------------- // --------------- // establish default options // --------------- var self = {}; var defaults = { properties : { prop : true, foo : "bar" }, methods : { main : function() { console.log(this.properties.foo); } } }; // --------------- // --------------- // Override default options and execute main() in the context // of our current options // --------------- this.init = function(options) { self = $.extend(true, {}, defaults, options); self.methods.main.call(self); }; this.init(options); // --------------- return this; } }); })(jQuery, window, document); $(window).load(function() { var options = { properties : { bar : "foo" }, methods : { main : function() { if(this.properties.prop) { console.log(this.properties.bar); } } } }; $.MyObject(options); });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

, 나는 가까웠다. 나는 deep extension이나 call() 함수에 익숙하지 않지만 그것들을 연구 할 것이다. 도와 줘서 고마워! –