jQuery UI widgetみたいにAPIを公開して拡張する
argumentsとか書いてるけど、ひとつしかないとき
function MyMethod(conf, arguments) { // return new MyMethod } // ... MyMethod.prototype._callAPI = function(api, arguments) { var self = this; if ( typeof self[api] !== 'function' ) { throw api + ' does not exist of MyMethod methods.'; } else if ( /^_/.test(api) && typeof self[api] === 'function' ) { throw 'Method begins with an underscore are not exposed.'; } return self[api](arguments); }; MyMethod.prototype._privateMethod = function() { // do something }; MyMethod.prototype.publicMethod = function() { // do something }; // $.fn extend jQuery.fn.myMethod = function(conf, arguments) { var my_method = this.data('myMethod'); if ( my_method ) { return my_method._callAPI(conf, arguments); } else { my_method = MyMethod(this, conf); this.data('myMethod', my_method); return this; } };
用意しとけば
var $my_method = $(hoge).myMethod({ ... }); // You cannot call private methods $my_method.myMethod('_privateMethod'); => Error thrown: Uncaught Method begins with an underscore are not exposed. $my_method.myMethod('publicMethod'); => OK