简体   繁体   中英

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 execution context. But, how can we access it value the same way if it is inside some function and not in the global execution context? For eg

function someFunction(someParameter) {
  var someVariable = "some value";
  // some code
}

I want to do something like someFucntionContext['someParameter'] or someFucntionContext['someVariable'] to access the value of those variables in the execution context of the someFucntion like I just did for the variable declared in the global context.

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']

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"])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM