我觉得这里有点无知,但我认为一些教育不会伤害我。
我简化了我的代码来概述问题 - 问题是当从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);
有什么想法吗?
答案 0 :(得分:3)
当您将其定义为init函数的参数时,您正在创建设置的本地副本:
// Here there is a global settings
init : function(settings) {
// Here there is a local settings
// Changes made to it won't affect the global
因此,当调用foo时,设置仍为0,并且您正在访问未定义的Number(0).x
。
只需删除设置的本地副本即可解决您的问题:
init : function(s) {
将settings || {}
更改为s || {}
答案 1 :(得分:0)
这是因为init函数接受了init
的本地参数设置如果foo要访问设置变量init sets,那么它应该调用foo
foo(settings);
function foo(settings)
或
如果您不想解决问题,那么init应该采用另一个参数名称,然后设置设置值。