开发者

JQuery plugin scope problems

开发者 https://www.devze.com 2023-04-01 18:56 出处:网络
I feel a little ignorant here, but I figure some education 开发者_Go百科won\'t hurt me. I have simplified my code to outline the issues - the problem is that when foo() is called from within the init

I feel a little ignorant here, but I figure some education 开发者_Go百科won't hurt me.

I have simplified my code to outline the issues - the problem is that when foo() is called from within the init method, it cannot access the supposed globals, a, b, c and settings. These are defined outside the method scope, so why are they not accessable?

For instance, settings is clearly defined just before the foo call, so why can foo not see settings?

(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);

Any ideas?


You are creating a local copy of settings when you define it as an argument to your init function:

// Here there is a global settings
init : function(settings) {
    // Here there is a local settings
    // Changes made to it won't affect the global

So when foo is called settings is still 0, and you are accessing Number(0).x which is undefined.

Just removing the local copy of settings will solve your problem:

init : function(s) {

And change settings || {} to s || {}


it's because the init function takes in a parameter settings which is local to init

if foo is to access the settings variable init sets then it should call foo

foo(settings);

function foo(settings) 

or

if you wan't a closure to fix your problem then init should take another parameter name, and then set the value of settings.

0

精彩评论

暂无评论...
验证码 换一张
取 消