2012-06-28 5 views
0

공개 프로토 타입 패턴을 사용하여 jQuery 플러그인을 개발하고 있습니다. 객체를 인스턴스화하는 데 문제가 있습니다. 다음, 플러그인의 코드 : 인스턴스화 할 때공개 프로토 타입 패턴을 사용하는 jQuery 플러그인

(function($) { 

var GammadiaCalendar = function(elem, options) { 
    this.elem = elem; 
    this.$elem = $(elem); 
    this.options = options; 
}; 

GammadiaCalendar.prototype = function() { 

    var defaults = { 
     message: 'Hello world!' 
    }, 

    init = function() { 

     this.config = $.extend({}, this.defaults, this.options); 

     this.displayMessage(); 

     return this; 
    }, 

    displayMessage = function() { 
     alert(this.config.message); 
    }; 

    return { 
     displayMessage : displayMessage 
    }; 


}; 

GammadiaCalendar.defaults = GammadiaCalendar.prototype.defaults; 

$.fn.GammadiaCalendar = function(options) { 
    return this.each(function() { 
     new GammadiaCalendar(this, options).init(); 
    }); 
}; 

})(jQuery) 

내가 GammadiaCalendar 받고 있어요는 정의되지 않습니다

var에 GC = 새로운 GammadiaCalendar ('아이디');

+0

이 노출되지 않기 때문에 당신이 포함 된 기능의 var gc = new GammadiaCalendar('id'); 밖에 할 수 없습니다

(function($) { //Because of this, everything here is "private" unless exposed anyway var defaults = { message: 'Hello world!' }; function init() { this.config = $.extend({}, defaults, this.options); this.displayMessage(); return this; } var GammadiaCalendar = function(elem, options) { this.elem = elem; this.$elem = $(elem); this.options = options; }; GammadiaCalendar.prototype = { displayMessage: function() { alert(this.config.message); }, constructor: GammadiaCalendar }; GammadiaCalendar.defaults = defaults; $.fn.GammadiaCalendar = function(options) { return this.each(function() { var instance = new GammadiaCalendar(this, options); init.call(instance); }); }; })(jQuery); 

주 이미 IIFE 안에 있기 때문에 패턴은 꽤 불필요합니다. 프로토 타입과 생성자는 내부에서만 사용할 수 있습니다. – Esailija

답변

1

문제는이 즉시 호출 된 이 아닌 함수 표현식으로 프로토 타입을 설정했기 때문입니다. 당신은 그것을 변경해야

GammadiaCalendar.prototype = (function() { 
    // your code here 
})(); // Execute it 

또한,이 라인이 작동하지 않을 것입니다 :

GammadiaCalendar.defaults = GammadiaCalendar.prototype.defaults; 

defaults 때문에 프로토 타입에 반환되지 않습니다.

공개 프로토 타입 패턴의 전체 구조가 잘못되었습니다. new GammadiaCalendar(this, options).init()에 의해 사용되는 init 함수는 비공개이므로 액세스 할 수 없습니다. 따라서, 프로토 타입은 다음과 같이 변경해야합니다 :

GammadiaCalendar.prototype = (function() { 
    var defaults = { 
    message: 'Hello world!' 
    }, 
    init = function() { 
    this.config = $.extend({}, this.defaults, this.options); 
    this.displayMessage(); 
    return this; 
    }, 
    displayMessage = function() { 
    alert(this.config.message); 
    }; 

    return { 
    defaults: defaults, 
    init: init, 
    displayMessage : displayMessage 
    }; 

})(); 

(그러나 물론, 실제 개인 기능을 내부에 없기 때문에 당신이 정말로,이 패턴 아무것도 얻은하지 않은이 방법을 수행하여 더 이상).

0

내가 그 패턴의 어떤 지점이 표시되지 않습니다, 당신은이 작업을 수행 할 수 있습니다 : 그것은