从嵌套函数访问类成员

新手上路,请多包涵

我在javascript中有这个类

var MyGird = Class.extend({
  classMemeber1 : "Some Value"
  ,clickEvent : function(){
        this.editor.on({
            afteredit: function() {
                //
                //  HOW TO I ACCESS classMemeber1 from here? ?
                //
                //
            }
        })
})

我如何从 afteredit 内部访问 classMemeber1 …

谢谢

原文由 fatnjazzy 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 263
2 个回答

您需要通过在变量中存储 this[1]来保存对对象调用 clickEvent 函数的引用。由于 _关闭_,它将在 afteredit 方法中可用。

 var MyGird = Class.extend({
    classMemeber1: "Some Value",
    clickEvent: function () {
        var self = this; // save object reference
        this.editor.on({
            afteredit: function () {
                // access classMemeber1 from here
                // by using the stored reference
                alert(self.classMemeber1);
            }
        });
    },
    // ...
});

[1] javascript 中的 this 运算符(注意: ‘this’ 不是运算符)

原文由 gblazex 发布,翻译遵循 CC BY-SA 3.0 许可协议

如果你写 ES6,你可以使用箭头函数: https ://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Functions/Arrow_functions

在您的示例中,应该类似于(未测试):

 var MyGird = Class.extend({
    classMemeber1: "Some Value",
    clickEvent: () => {
        this.editor.on({
            afteredit: () => () {
                alert(this.classMemeber1);
            }
        });
    },
    // ...
});

原文由 Nico Toub 发布,翻译遵循 CC BY-SA 3.0 许可协议

推荐问题