我有一个具有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;
            }
        }
    }

最佳答案

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

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


在此示例中,我依靠这样的事实:外部函数将像这样被调用:

MessageHelper.index()


因此在其中,this实际上将是MessageHelper。因此,MessageHelper也将位于索引返回的函数中的this内。

如果您打算做一些事情,例如将index函数作为参数传递到某个地方,则不会按预期方式调用它,并且整个过程都会失败。在这种情况下,您应该绑定到MessageHelper:

var MessageHelper = {
  index : function(){}.bind(MessageHelper);
}

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

关于javascript - javascript对象变量范围,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/22327480/

10-10 15:17