奇怪的行为,如Javascript中的动态范围

时间:2018-03-23 13:48:03

标签: javascript scope dynamic-scope

我有以下测试代码:

// Generated by CoffeeScript 2.2.3
(function() {
  var t, test;

  test = function() {
    var dynamic_scoped_function, nested_function, vairable_function;
    dynamic_scoped_function = function() {
      return console.log(`variable function value: ${vairable_function()}`);
    };
    vairable_function = function() {
      return "not in nested function";
    };
    nested_function = function() {
      var nested_caller;
      vairable_function = function() {
        return "in nested function";
      };
      nested_caller = function() {
        console.log("calling dynamic scoped function from nested...");
        return dynamic_scoped_function();
      };
      return {
        vairable_function,
        nested_caller
      };
    };
    return {
      dynamic_scoped_function,
      nested_function
    };
  };

  t = test();

  t.dynamic_scoped_function();

  t.nested_function().nested_caller();

}).call(this);

使用node.js运行时的结果是

variable function value: not in nested function
calling dynamic scoped function from nested...
variable function value: in nested function

variable_function中解析名称dynamic_scoped_function时,它取决于调用堆栈,但不会像我期望的那样静态地解析为外部堆栈。

在我看来,这种行为很愚蠢,因为我无法预见dynamic_scoped_function将被调用的地方。这种语言的设计是这样的吗?或者我只是误解了一些东西?

感谢您的帮助。

1 个答案:

答案 0 :(得分:1)

执行nested_function后,它会为vairable_function [sic]变量分配一个新函数。变量仍然相同,但它现在保持一个新值。这有同样的效果:

t.nested_function();          // replaces vairable_function
t.dynamic_scoped_function();  // accesses the redefined vairable_function

或简化:

var foo = 'bar';
console.log(foo);
foo = 'baz';
console.log(foo);