How do I scope variables properly in jQuery?

Posted by safetycopy on Stack Overflow See other posts from Stack Overflow or by safetycopy
Published on 2010-05-28T20:38:57Z Indexed on 2010/05/28 20:42 UTC
Read the original article Hit count: 184

Filed under:
|
|

I'm working on a jQuery plugin, but am having some trouble getting my variables properly scoped. Here's an example from my code:

(function($) {

$.fn.ksana = function(userOptions) {
    var o = $.extend({}, $.fn.ksana.defaultOptions, userOptions);

    return this.each(function() {
        alert(rotate()); // o is not defined
    });
};

function rotate() {
    return Math.round(o.negRot + (Math.random() * (o.posRot - o.negRot)));
};

$.fn.ksana.defaultOptions = {
    negRot: -20,
    posRot: 20
};

})(jQuery);

I'm trying to get the private function rotate to be able to see the o variable, but it just keeps alerting 'o is not defined'. I'm not sure what I'm doing wrong.

© Stack Overflow or respective owner

Related posts about JavaScript

Related posts about jQuery