javascript 从嵌套函数访问类成员
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3949887/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Access class members from nested functions
提问by fatnjazzy
i have this class in javascript
我在javascript中有这个类
var MyGird = Class.extend({
classMemeber1 : "Some Value"
,clickEvent : function(){
this.editor.on({
afteredit: function() {
//
// HOW TO I ACCESS classMemeber1 from here? ?
//
//
}
})
})
how do i access classMemeber1 from inside of afteredit...
Thanks
我如何从 afteredit 内部访问 classMemeber1 ......
谢谢
回答by gblazex
You need to save a reference to the object invoking clickEventfunction by storing this[1]in a variable. It will be available inside the aftereditmethod because of closure.
您需要clickEvent通过将this[1]存储在变量中来保存对对象调用函数的引用。afteredit由于close,它将在方法内部可用。
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] this operator in javascript(note: 'this'is not an operator)
[1] javascript 中的 this 运算符(注意:'this'不是运算符)
回答by Nico Toub
If you write ES6, you can use arrow functions: https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Functions/Arrow_functions
如果你写 ES6,你可以使用箭头函数:https: //developer.mozilla.org/en/docs/Web/JavaScript/Reference/Functions/Arrow_functions
In your example, should be something like (not tested):
在您的示例中,应该类似于(未测试):
var MyGird = Class.extend({
classMemeber1: "Some Value",
clickEvent: () => {
this.editor.on({
afteredit: () => () {
alert(this.classMemeber1);
}
});
},
// ...
});

