Tuesday 23 May 2017

Inject variables into function scope

Ho do i call a function injecting into its scope arbitrary variables / functions? I want to define an "update" function that can freely call a series of functions, but they have to be defined and bond in another scope.

I tried with with but it doesn't work.

Also, I know there are a tons of solutions like passing the object whose functions to call or define a list of arguments and bind them, but since "update" has to be defined by the user, its signature must be just a simple function with no arguments (just like in the code below) but it has to have access to a long list of functions with an arbitrary binding.

function obj (size) {
    this.printSize = function () {
        console.log(size);
    }
}

const obj1 = new obj(1);
const obj2 = new obj(2);

function update () {
    printSize();
}

with(obj1) {
    update();
}

with(obj2) {
    update();
}


via pistacchio

No comments:

Post a Comment