1

I'm trying to find a way to set a custom environment to a function in Node.JS.

For example:

var context = { // Define env for the function
    foo: function(){
        return "bar"
    },
    test: function(arg){
        doThings(arg);
    }
}

var func = function(){ // Define the function
    test(foo());
}

setCustomEnv(func,context) // Inject the function into the function (and if possible run it)
Ale32bit
  • 31
  • 3
  • can you describe what you want? – Pankaj Bisht Apr 02 '18 at 12:58
  • I'm trying to find a library or something similar to inject a custom environment to a function, the environment should only work on that function and everything called from it. The function that injects should at least support 2 args which are the function and the custom env. I hope I've explained well what I meant. – Ale32bit Apr 02 '18 at 13:01
  • Possible duplicate of [How do I pass the this context to a function?](https://stackoverflow.com/questions/3630054/how-do-i-pass-the-this-context-to-a-function) – t.niese Apr 02 '18 at 13:05
  • For that you can use mixin.. – Pankaj Bisht Apr 03 '18 at 07:38

1 Answers1

0

It would only work if you change test(foo()); to this.test(this.foo());

var context = { // Define env for the function
    foo: function(){
        return "bar"
    },
    test: function(arg){
        doThings(arg);
    }
}

var func = function(){ // Define the function
    this.test(this.foo());
}

Then you could just write:

func.call(context); 

That way func would be called as if it is part of conext.

t.niese
  • 32,069
  • 7
  • 56
  • 86