【问题标题】:javascript object variable scopejavascript对象变量范围
【发布时间】:2014-03-11 13:43:20
【问题描述】:

我有一个带有 idx var 的 MessageHelper 对象。现在我想从索引方法访问和修改它。我认为“这个”会做,但我得到的是 NaN。有什么线索吗?

var MessageHelper = {
        idx: 8,
        formatDate: function(){
            return function(text, render) {
                // // parse date
                var date = $.trim(render(text));
                var mom = moment(date);
                return mom.format("D/M/YY");
            }
        },
        formatDateTime: function(){
            [...]
        },      
        getImportance: function(){
            [...]
        },
        index: function(){
            return function(text, render) {
                this.idx++;
                return this.idx;
            }
        }
    }   

【问题讨论】:

    标签: javascript oop scope


    【解决方案1】:

    函数内this 的值取决于该函数的调用方式。如果您希望函数始终以某个值作为this 调用,最简单的方法是使用Function.prototype.bind:

        index: function(){
            return function(text, render) {
                this.idx++;
                return this.idx;
            }.bind(this); // <--- HERE
        }
    

    在这个例子中,我依赖于这样一个事实,即外部函数将被这样调用:

    MessageHelper.index()
    

    所以在其中,this 实际上是 MessageHelper。因此,MessageHelper 也将在 index 返回的函数中为this。

    如果你打算做一些事情,比如将索引函数作为参数传递到某个地方,它就不会按预期被调用,整个事情都会失败。在这种情况下,您应该绑定到 MessageHelper:

    var MessageHelper = {
      index : function(){}.bind(MessageHelper);
    }
    
    var myIndex = MessageHelper.index;
    myIndex(); // this will return the correct function, bound to MessageHelper
    

    【讨论】:

      【解决方案2】:

      index 返回的函数内部的作用域(this)就是函数本身。外部索引,this 指的是MessageHelper。

      所以基本上你必须这样做:

      var MessageHelper = {
              idx: 8,
              index: function(){
                  var self = this; // MessageHelper
                  return function(text, render) {
                      self.idx++;
                      return self.idx;
                  }
              }
          }   
      

      您也可以使用bind,但旧版浏览器不支持它。

      提示:如果您没有定义构造函数,则惯例是使用小写字母命名对象。在你的情况下 messageHelper.

      【讨论】:

        猜你喜欢
        • 2013-05-29
        • 2012-01-21
        • 2013-10-01
        • 1970-01-01
        • 2012-08-10
        • 1970-01-01
        • 2020-12-21
        • 2020-02-07
        • 2012-12-23
        相关资源
        最近更新 更多