在Javascript中创建变量的实例并在匿名函数中访问变量

时间:2014-07-28 11:17:18

标签: javascript jquery

我有以下JavaScript代码:

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

我有两个问题:

1)如何创建变量的实例,以便我可以拥有两个独立的对象,每个对象都有自己唯一的变量值?

示例:

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

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

2)如何从对象中的函数内的jQuery插件访问匿名函数内的变量。通过this没有帮助。

2 个答案:

答案 0 :(得分:1)

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

你也可以用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})

并从不同上下文中的回调访问this,将其包含在某个变量中。 所以最终代码如下:

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

答案 1 :(得分:1)

您需要将代码从对象文字更改为构造函数,并确保在this函数中引用正确的func1

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

DEMO