Javascript 构造jQuery插件
我正在编写一个jQuery插件,经常会被某些函数的范围弄糊涂(这是使用jS的传统) 一个简短的例子应该有助于:Javascript 构造jQuery插件,javascript,jquery,plugins,scope,structure,Javascript,Jquery,Plugins,Scope,Structure,我正在编写一个jQuery插件,经常会被某些函数的范围弄糊涂(这是使用jS的传统) 一个简短的例子应该有助于: (function ( $ ) { var methods = { init: function ( options ) { var settings = $.extend ({ a: 100, b: 200 }, options);
(function ( $ ) {
var methods = {
init: function ( options ) {
var settings = $.extend ({
a: 100,
b: 200
}, options);
return this.each(function(){
var $this = $(this);
var return_value = $this.plugintest("method_1", settings);
$this.plugintest("method_2", settings, return_value);
});
},
method_1 : function ( settings ) {
var method_1_value_1 = settings.a * 10,
method_1_value_2 = settings.a * 20;
return method_1_value_1;
},
method_2 : function ( settings, old_return_value ) {
// WHAT IF I WANT BOTH method_1_value_1 AND method_1_value_2 in here?
}
};
$.fn.plugintest = function (method) {
if ( methods[method] ) {
return methods[method].apply( this, Array.prototype.slice.call ( arguments, 1 ) );
} else if ( typeof method === 'object' || ! method ) {
return methods.init.apply( this, arguments );
} else {
$.error( 'Method ' + method + ' does not exist in jQuery.robottest' );
}
};
}) (jQuery);
见方法2。我想访问我在方法_1中创建的值,但是我只能返回1个值-我应该创建某种类型的全局变量吗?执行此操作的“最佳”方法是什么?函数中定义的变量将在函数范围内。在函数之前声明的任何内容都将在父作用域中。父范围(取决于变量声明)将由父范围内的函数可见
因此,如果您在父函数中声明变量,并且不在内部函数中再次声明它们,将导致从内部函数访问这两个变量。变量在声明它们的函数中可见(即它们的
var
语句出现的函数)在该函数中声明的任何函数中
下面是一个例子:
(function () {
var foo;
// foo is visible here, bar is not
// declare variables that should be visible to your whole plugin here
var methods = {
a: function () {
var bar;
// foo and bar are both visible here
},
b: function () {
// foo is visible here, bar is not
}
};
}());
// neither foo nor bar are visible here
永远不要使用全局变量(即未在函数中用
var
语句声明的变量)。这些代码对文档中的所有其他代码都可见。但是,只要您将所有内容都包含在函数中,并且始终使用var
,您就安全了。这是最好的开始:您可以从方法1
返回一个对象,其中包含每个值的属性。这样做可以吗?我试过这样做,但被告知这是一个糟糕的练习。好的,很好-谢谢。我们期待一个复杂的解决方案,但这很容易!这不是唯一的方法(无论如何,基于所讨论的代码)。您可以从method_1
返回对象,例如返回{value1:method_1_value_1,value2:method_2_value_2}代码>。这真的取决于偏好。如果method\u 1\u value\u 2
只在method1
和method2
中使用,那么在更广的范围内使用它是没有意义的。你被什么人或谁告知这是不好的做法?我怀疑你被告知全局变量是不好的做法。我已经更新了答案来解释差异。