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:
functionevalWith(obj, func) {
with(obj) returneval('(' + func + ')')();
}
// Example:functionobj(size) {
this.printSize = function() {
console.log(size);
}
}
const obj1 = newobj(1);
functionupdate() {
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
functionobj (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
functionobj (size) {
printSize = function () {
console.log(size);
}
}
functionupdate () {
printSize();
}
const obj1 = newobj(1);
with(obj1) {
update();
}
const obj2 = newobj(2);
with(obj2) {
update();
}
Post a Comment for "Inject Variables Into Function Scope"