Skip to content Skip to sidebar Skip to footer

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

Solution 1:

Viewer discretion is advised:

function evalWith(obj, func) {
  with(obj) return eval('(' + func + ')')();
}

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

const obj1 = new obj(1);

function update() {
  printSize();
}

evalWith(obj1, update); // 1

Solution 2:

Variable binding in javascript is set upon function creation, not calling.

So, your only effective options are to namespace the variables you need in an object, and populate that later. Or you can set the variables to the global namespace (e.g) window.

There's no way to get the contents of a function and re-eval it later, unfortunately.

The most you can do is change the values of the arguments passed into the function, using call or apply as mentioned by others.


Solution 3:

Have you tried

function obj (size) {
    this.printSize = function () {
        // presumably do something with "this"
        console.log(size);
    }.bind(this);
}

Solution 4:

You will need to make an instance of the obj before each with call

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




function update () {
    printSize();
}

const obj1 = new obj(1);

with(obj1) {

    update();
}

const obj2 = new obj(2);

with(obj2) {

    update();
}

Post a Comment for "Inject Variables Into Function Scope"