0

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.

2 Answers 2

1
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;
           });
        }
    }
Sign up to request clarification or add additional context in comments.

1 Comment

Excellent, thanks a lot for the quick response Gena.
1

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

Comments

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.