简体   繁体   中英

How do I access a jQuery plugin variable from within method?

I'm trying to get write a simple jQuery plugin, I've come to a stumbling block though in that I'm not sure how to access variables on the plugin from within a method for that plugin.

(function($) {
    $.fn.testPlugin = function() {
        var testVar = "Hello World";
        alert(testVar);
        $.fn.testPlugin.testMethod();
    };

    $.fn.testPlugin.testMethod = function() {
        alert($.fn.testPlugin.testVar);
    };
}(jQuery));

$("body").testPlugin();

FIDDLE HERE

This code first alerts "Hello World" then "undefined" (so attempting to access it from within the method returns an empty variable), is there any way to access testVar from within the testMethod? Is this not possible? Am I going about this in the wrong way?

You can put variable in the outer scope - scope of your self invoking function.

(function($) {
    var testVar;
    $.fn.testPlugin = function() {
        testVar = "Hello World";
        alert(testVar);
        $.fn.testPlugin.testMethod();
    };

    $.fn.testPlugin.testMethod = function() {
        alert(testVar);
    };
}(jQuery));

$("body").testPlugin();

This could be more desirable approach if for example you do not want your variable to be accessible by any other code except your plugin. Fiddle: http://jsfiddle.net/79sg8es1/ .

You are creating a local variable inside your first method. That makes it's scope restricted to the method itself.

Instead, you should actually create that variable with reference to the plugin like this :

$.fn.testPlugin.testVar = "Hello World";

Your updated plunker goes here : http://jsfiddle.net/5zt9ps20/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM