2017-09-16 36 views
0

我正在尝试创建一个由构造时设置的函数修改的类。 问题是,我如何获得这个函数来修改它分配给它的类的私有字段。 我已经创建了一个简化的代码来解释:如何将函数传递给稍后修改所述类的类

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是可以接受的。

+0

看起来你需要阅读更多关于** **关闭。 –

+0

@ibrahimmahrir你能推荐和文章/指南? – Airwavezx

+1

[** this **](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Closures)和[** this **](https://stackoverflow.com/questions/ 111102 /怎么办 - JavaScript的关闭工作)。 –

回答

1

外部函数没有办法让本地变量a没有通过。函数试图在定义它的地方找到变量,这意味着外部funk隐式地不能访问任何变量foo。如果a是一个对象变量,您可以通过上下文绑定来访问它。

您还需要将参考a也传递给函数。

let funk = function(v, array) { 
    array.push(v); 
} 

并呼吁通过

function executer(v) { 
    func(v, a); 
} 

代码

foo = function(options) { 
 
    let {func} = options; 
 
    let a = []; 
 

 
    function executer(v) { 
 
    func(v, a); 
 
    } 
 

 
    return {executer}; 
 
}; 
 

 

 
let funk = function(v, array){ 
 
    array.push(v); 
 
} 
 

 
let bar = new foo({ 
 
    func: funk 
 
}); 
 

 
bar.executer(1);

+0

谢谢你的回答!在此期间我做了类似的事情,除了我将“this”引用传递给该函数。以下是代码:https://jsfiddle.net/0hpLgLuz/2/ - 您认为哪种解决方案更安全? – Airwavezx

+0

将变量传递给它。没有什么安全的。如果你将某物推入阵列,那么你就故意改变阵列。 –

相关问题