【问题标题】:JavaScript change ownership of thisJavaScript 更改 this 的所有权
【发布时间】:2012-08-03 20:48:47
【问题描述】:

我有一个对象,类似这样的

var Egg = function(){

   this.test = $(.slider .label);

    $('.slider').slider({
       min: 1,
       value: 2,
       step: 1,
       value: 10,
       slide: function(){
         this.test.html(ui.value)
       }
    });

}

我想在滑块对象中使用我的变量测试。然而,在其当前形式中,this 指的是滑块而不是我的 egg 对象,因此当滑块移动时尝试使用 this.test 会导致未定义。

如何让this 引用我的对象而不是滑块。

谢谢

【问题讨论】:

    标签: javascript oop this


    【解决方案1】:

    this 具有动态范围,因此在幻灯片函数内部,this 指的是调用该函数的任何对象。这不等于定义函数时所等于的值(我不知道我是否说得很清楚......阅读此http://hoolihan.net/blog-tim/2009/02/17/static-vs-dynamic-scope/)。但是,您可以将其保存在另一个变量中并以这种方式访问​​它

    var Egg = function(){
    
       var self = this;
    
       this.test = $(.slider .label);
    
        $('.slider').slider({
           min: 1,
           value: 2,
           step: 1,
           value: 10,
           slide: function(){
             self.test.html(ui.value)
           }
        });
    
    }
    

    【讨论】:

      【解决方案2】:

      这是 jQuery 吗?使用$.proxy...

      $('.slider').slider({
         min: 1,
         value: 2,
         step: 1,
         value: 10,
         slide: $.proxy(function(){
           this.test.html(ui.value)
         }, this)
      });
      

      没有 jQuery,你可以使用Function.prototype.bind...

      $('.slider').slider({
         min: 1,
         value: 2,
         step: 1,
         value: 10,
         slide: function(){
           this.test.html(ui.value)
         }.bind(this)
      });
      

      【讨论】:

        猜你喜欢
        • 2012-04-03
        • 2016-10-01
        • 1970-01-01
        • 1970-01-01
        • 2010-09-21
        • 1970-01-01
        • 1970-01-01
        • 2017-01-05
        • 2017-01-08
        相关资源
        最近更新 更多