jQuery插件共享函数和变量
我正在开发一个jQuery插件,对于在同一名称空间内的方法之间共享函数和变量有点困惑。我知道以下措施将起作用:jQuery插件共享函数和变量,jquery,plugins,Jquery,Plugins,我正在开发一个jQuery插件,对于在同一名称空间内的方法之间共享函数和变量有点困惑。我知道以下措施将起作用: (function($){ var k = 0; var sharedFunction = function(){ //... } var methods = { init : function() { return this.each(function() {
(function($){
var k = 0;
var sharedFunction = function(){
//...
}
var methods = {
init : function() {
return this.each(function() {
sharedFunction();
});
},
method2 : function() {
return this.each(function() {
sharedFunction();
});
}
};
$.fn.myPlugin = function(method) {
// Method calling logic
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 here');
}
};
})(jQuery);
然而,我想知道是否有更好的方法来做到这一点。虽然我知道变量“k”和函数“sharedFunction”在技术上不是全局的(因为它们不能在插件之外直接访问),但这看起来最简单
我知道$.data是一个选项,但是如果你有大量的变量和函数需要通过插件中的多个方法访问,这看起来可能会变成一团混乱
如有任何见解,将不胜感激。谢谢 Javascript中一个(可以说)更常见的缺陷是,{}
没有像其他C风格语言那样定义作用域;函数可以
记住这一点,除了使变量成为全局变量外,有两种方法(我通常使用)在两个单独的函数之间共享变量:
在公共函数中声明函数
这就是你在上面演示的内容。您正在另一个函数(定义范围)中声明两个函数。容器函数的子级中声明的任何内容都可以在其作用域中的任何位置使用,包括两个内部函数的作用域
// this is a self-calling function
(function () {
var foo;
var f1 = function () {
// foo will be accessible here
},
f2 = function () {
// ... and foo is accessible here as well
}
})();
老实说,这一点也不“简单”,通常是为了代替不能在Javascript中定义除函数作用域以外的作用域
名称空间公用成员
您可以在全局范围内定义一个对象,然后用变量/函数扩展它。你确实必须走向全球,但你正在通过确保只做一次来最小化你的足迹
使用$().data()
似乎是可行的,但尽管它确实有它的用途,但我还是不建议增加额外的开销来提供您描述的功能,因为它可以通过简单的语言机制轻松实现(而且是本机实现的)(尽管可读性需要一点习惯)
window.app = {
foo : 'bar'
};
(function () {
var f1 = function () {
// app.foo will be accessible here
};
})();
(function () {
var f2 = function () {
// ... and here as well, even though we're
// in a totally different (parent) scope
};
})();