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
}
}
}
});
});
나는 내가하는 일을 과도하게 복잡하게 만들었습니다. 이 시점에서, 나는 아마 이것을 할 더 좋은 방법이 있다고 생각하고 있습니다.
의견이 있으십니까?
아 남자