简体   繁体   English

在javascript中关闭词法作用域

[英]switch off lexical scoping in javascript

Is it possible to change the lexical scoping of javascript so that functions use the variable scope that is in effect when they are evoked not when they were defined? 是否可以更改javascript的词法作用域,以使函数使用在引发它们时(而不是在定义它们时)有效的变量作用域? In a nutshell can I change the scope chain associated with a function? 简而言之,我可以更改与功能关联的作用域链吗?

An example for this: I would like to be able to execute something like this without getting the error message, that y is not defined: 一个示例:我希望能够执行类似这样的操作而不会收到错误消息,即未定义y:

function f(){y+2};
function g(){
 var y=2;
 f();
 return y;
}
g();

Your question may be due to the misunderstanding of your issue. 您的问题可能是由于对您的问题的误解。 y is not defined in a functional scope of f() , and you never assign a value to it. yf()的功能范围内未定义,并且您永远不会为其分配值。 The y in g() is scoped to that function. g()y限于该函数。

In your example: 在您的示例中:

function f(){ y+2 };
function g(){
  var y=2;
  f();
  return y;
}
g();

If g() used the global y , then y in f() will be defined at run-time. 如果g()使用全局y ,则f() y将在运行时定义。 Drop the var keyword in g() to create a global y at compilation-time. 在编译时将var关键字放在g()以创建全局y

function f(){ y+2 };
function g(){
  y=2;
  f();
  return y;
}
g();

NOTE: Creating globally scoped variable like this is possible, but NOT recommended. 注意:可以像这样创建全局范围的变量,但建议这样做。 Since your example is contrived and only being used to understand scope, it won't hurt anything. 由于您的示例是人为设计的,仅用于理解范围,因此不会对您造成任何伤害。

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

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