How Can We Get The Execution Context Of A Function?
Let say we declare a variable in the global context, like so: var someVariable = 'someValue'; We can always access its value like window['someVariable'] as it is in the global exe
Solution 1:
That's not possible without returning objects or instantiating the function and accessing the property.
Global variables are automatically a property of the window
object, provided you use var
and not let
or const
. Such as root level functions being automatically a method of the window
object. But functions do not behave like primitive objects. You need to do something like
function Favorites(){
return{
food: "burrito",
color: "gray"
}
}
var fav = Favorites();
var favfood = fav.food; //fav['food']
OR
function Favorites(){
this.food = "burrito";
this.color = "gray";
}
var fav = new Favorites();
var favfood = fav.food; //fav['food']
And like so
var favfood = window.fav.food;
var favcolor = window['fav']['color']
Solution 2:
One of the approach could be exposing certain properties of the function itself.
function fn(){
fn.num = 100;
}
//access fn.num
console.log(fn["num"])
You can control which properties you want to expose from the function itself. For example,
function doSomething(num, addStr){
//expose num
doSomething.num = num;
var str = "Hello ";
if(addStr){
str += addStr;
}
//expose str
doSomething.str = str;
}
//set num
doSomething(100);
//access num
console.log(doSomething.num)
console.log(doSomething["num"])
//set num and str
doSomething(200, "Jerry!")
//access str
console.log(doSomething["str"])
Post a Comment for "How Can We Get The Execution Context Of A Function?"