0

I am trying to create a class that is modified by a function that is set upon construction. The problem is, how do I get this function to modify the private fields of the class it's assigned to. I have created a simplified code to explain:

https://jsfiddle.net/9zjc0k9e/ (same code as below):

The class to be modified:

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};
};

Main:

//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

The error I'm getting is: Uncaught ReferenceError: a is not defined. I hope I have cleared the problem enough, is there a way to get this done? Hack-ish is acceptable.

Airwavezx
  • 323
  • 1
  • 9

1 Answers1

1

There is no way for the outer function to see the local variable a without passing. The function tries to find the variables in that place where it is defined, means that the outer funk has no access any variable of foo implicitly. If a was an object variable you could access it via context binding.

You need to pass the reference of a too to the function.

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

And call via

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

Your Code

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);
Suren Srapyan
  • 66,568
  • 14
  • 114
  • 112
  • Thank you for your answer! I have done something similar in the mean time, except that I'm passing 'this' reference to the function. Here is the code: https://jsfiddle.net/0hpLgLuz/2/ - which solution do you think is safer? – Airwavezx Sep 16 '17 at 18:57
  • Pass the variable into it. There is nothing about safe. If you `push` something into the array, so you change your array intentionally. – Suren Srapyan Sep 16 '17 at 18:59