Liron Harel
Liron Harel

Reputation: 11247

Create instances of a variable in Javascript and access variable within an anonymous function

I have the following JavaScript code:

var objSample = {
   variable: 10,
   func1 : function(){
       someJQueryPlugin(1, function(){
             this.variable; // this doesn't work, don't have access
       });
    }
}

I have two questions:

1) How can I create an instance of the variable so I can have two stand alone objects, each one with its own unique variable values?

Example:

var obj1 = new objSample();
obj1.variable = 1;

var obj2 = new objSample();
obj2.variable = 2;

2) How can I have access to the variable inside an anonymous function from a jQuery plugin inside a function in the object. passing this didn't help.

Upvotes: 0

Views: 41

Answers (2)

Andy
Andy

Reputation: 63524

You need to change the code from an object literal to a constructor function and ensure that you reference the right this in the func1 function.

function ObjSample() {
  this.variable = 10;
  this.func1 = function () {
    var _this = this;
    someJQueryPlugin(1, function () {
      _this.variable;
    });
  }
}

DEMO

Upvotes: 1

Gena Moroz
Gena Moroz

Reputation: 954

var objSample = function(){
  this.variable = 10
   this.func1 = function(){
       someJQueryPlugin(1, function(){
             this.variable; <-- this doesn't work, don't have access
       });
    }
}

also you can extend constructor with params

 var objSample = function(options){
  this.variable = options.val
   this.func1 = function(){
       someJQueryPlugin(1, function(){
             this.variable; <-- this doesn't work, don't have access
       });
    }
}
var obj1  = new objSample ({val:1})
var obj2  = new objSample ({val:2})

and to access this from callbacks in different context, enclose this to some variable. So final code looks like:

 var objSample = function(options){
      var self = this;
      self.variable = options.val
       self.func1 = function(){
           someJQueryPlugin(1, function(){
                 self.variable;
           });
        }
    }

Upvotes: 1

Related Questions