我覺得這裏有點無知,但我認爲一些教育不會傷害到我。JQuery插件範圍問題
我簡化了我的代碼來概述問題 - 問題是,當從init方法內調用foo()時,它不能訪問假定的全局變量a,b,c和設置。這些是在方法範圍外定義的,爲什麼它們不可訪問?
例如,在foo調用之前明確定義了設置,那麼foo爲什麼看不到設置?
(function(jQuery) {
a = new Date();
var b;
var c = 1;
settings = 0; // Here or not - same issue
var methods = {
init : function(settings) {
c = $(this);
settings = jQuery.extend({
id: Math.floor(Math.random()*1001),
x: 3;
etc: 2
}, settings || {});
m = 1;
foo();
}
};
function foo()
{
x = settings.x; // settings is not defined
var n = c.m;
return x;
}
jQuery.fn.bar= function(method) {
if (methods[method]) // If we have a method that exists
{
return methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
}
else if (typeof method === 'object' || ! method) // Otherwise if we get passed an object (settings) or nothing, run the init.
{
return methods.init.apply(this, arguments);
}
else
{
$.error('Method ' + method + ' does not exist'); // Otherwise we have an error.
}
};
})(jQuery);
任何想法?
這並不重要,但你沒有var =賦值,你聲明頁面頂部的設置 – jammypeach
在你的例子中,「settings」沒有定義,或者「settings.x」沒有定義?在foo()中,設置應該等於0,但settings.x應該是未定義的...你能確認嗎? – Timbo
@Timbo - 我確認...設置= 0,settings.x是未定義的。什麼是範圍? –