【问题标题】:JQuery plugin scope problemsJQuery 插件范围问题
【发布时间】: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


【解决方案1】:

当您将其定义为 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 被调用时,settings 仍然是 0,而你访问的是未定义的 Number(0).x

只需删除设置的本地副本即可解决您的问题:

init : function(s) {

并将settings || {} 更改为s || {}

【讨论】:

  • 100% - 现在我看到它是有道理的。我没有注意到我正在覆盖它。
【解决方案2】:

这是因为 init 函数接受了 init 本地的参数设置

如果 foo 要访问设置变量 init sets 那么它应该调用 foo

foo(settings);

function foo(settings) 

如果你不想用闭包来解决你的问题,那么 init 应该采用另一个参数名称,然后设置设置的值。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-04-23
    • 2011-08-27
    • 1970-01-01
    • 2011-11-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多