我正在尝试创建一个由构造时设置的函数修改的类。 问题是,我如何获得这个函数来修改它分配给它的类的私有字段。 我已经创建了一个简化的代码来解释:如何将函数传递给稍后修改所述类的类
https://jsfiddle.net/9zjc0k9e/(相同的代码如下):
的类进行修改:
foo = function(options) {
let {func} = options; //The function we send on construction
let a = []; //The variable we are trying to modify with the function
function executer(v) {
func(v);
}
return {executer};
};
主要:
//The function we will send when constructing:
let funk = function(v) {
a.push(v); // <- this 'a' is the private member of the class we wanna modify
}
//Construct:
let bar = new foo({
func: funk
});
//Run the function we sent through the public class function assigned to that
bar.executer(1); //<-- Uncaught ReferenceError: a is not defined
误差我得到的是:Uncaught ReferenceError: a is not defined
。 我希望我已经清除了这个问题,有没有办法做到这一点? Hack-ish是可以接受的。
看起来你需要阅读更多关于** **关闭。 –
@ibrahimmahrir你能推荐和文章/指南? – Airwavezx
[** this **](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Closures)和[** this **](https://stackoverflow.com/questions/ 111102 /怎么办 - JavaScript的关闭工作)。 –