简体   繁体   中英

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.

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;
           });
        }
    }

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

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