1

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?

2 Answers 2

2

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/.

Sign up to request clarification or add additional context in comments.

Comments

1

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/

1 Comment

Thanks! I knew I must have been missing something obvious.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.