简体   繁体   English

我们如何获取函数的执行上下文?

[英]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.我们总是可以像window['someVariable']一样访问它的值,因为它在全局执行上下文中。 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.我想要做喜欢的事, someFucntionContext['someParameter']someFucntionContext['someVariable']访问这些变量的值在执行方面someFucntion像我刚才没有为变量在全球范围内宣布。

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 .全局变量自动是window对象的属性,前提是您使用var而不是letconst Such as root level functions being automatically a method of the window object.例如根级函数自动成为window对象的一个​​方法。 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"])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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