私は jQuery プラグインのプラグイン ボイラー プレートを見てきましたが、問題はないと思いますが、設計に 1 つの大きな欠陥があるか、私には理解できないことがあるかもしれません。
現時点でプラグインを作成する場合、プラグインのみがアクセスできるパブリックに公開されたメソッドとプライベート メソッドを簡単に定義できます。
ボイラープレートで似たようなことをしようとしたとき、私は挫折しました。
;(function ( $, window, document, undefined ) {
// Create the defaults once
var
pluginName = "defaultPluginName",
defaults = {
propertyName: "value"
};
// The actual plugin constructor
function Plugin ( element, options ) {
this.element = element;
this.settings = $.extend( {}, defaults, options );
this.defaults = defaults;
this.name = pluginName;
this.init();
}
Plugin.prototype.init = function() {
console.log('init')
console.log(this)
this.yourOtherFunction();
}
Plugin.prototype.yourOtherFunction = function () {
console.log('yourOtherFunction')
console.log(this)
this.yourOtherFunction2();
}
Plugin.prototype.yourOtherFunction2 = function () {
privateFunction().bind(this)
}
var privateFunction = function() {
console.log('private')
console.log(this)
}
// A really lightweight plugin wrapper around the constructor,
// preventing against multiple instantiations
$.fn[ pluginName ] = function ( options ) {
return this.each(function() {
if ( !$.data( this, "plugin_" + pluginName ) ) {
$.data( this, "plugin_" + pluginName, new Plugin( this, options ) );
}
});
};
})( jQuery, window, document );
$(document).defaultPluginName()
とにかく、関数 'privateFunction' のスコープはウィンドウ オブジェクトであることがわかりますが、私ができるようにしたいのは、それをプラグイン インスタンス、または基本的にプロトタイプ メソッドの 'this' にスコープすることです。
私がやりたくないのは、関数の引数として各プライベート関数にスコープを渡すことです!
では、どうすればスコープをバインドできますか?
Console output
init
Plugin { element=document, settings={...}, defaults={...}, more...}
yourOtherFunction
Plugin { element=document, settings={...}, defaults={...}, more...}
private
Window index.html <-- I want Plugin, not window