【发布时间】:2011-09-02 09:48:45
【问题描述】:
我觉得这里有点无知,但我认为一些教育不会伤害我。
我已经简化了我的代码以概述问题 - 问题是当从 init 方法中调用 foo() 时,它无法访问假定的全局变量、a、b、c 和设置。这些是在方法范围之外定义的,那么为什么它们不可访问?
例如,settings 是在 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= 赋值
-
在您的示例中是“设置”未定义,还是“settings.x”未定义?在 foo() 中设置应该等于 0,但是 settings.x 应该是未定义的……你能确认一下吗?
-
@Timbo - 我确认... settings = 0,settings.x 未定义。范围是怎么回事?
标签: javascript jquery jquery-plugins scope