-1

我有以下测试代码:

// 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

似乎当 namevariable_function被解析时dynamic_scoped_function,它取决于调用堆栈,但没有像我期望的那样静态解析到外部堆栈。

在我看来,这种行为是愚蠢的,因为我无法预见会在哪里dynamic_scoped_function被调用。这种语言是否设计成这样?还是我只是误解了什么?

谢谢你的帮助。

4

1 回答 1

1

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

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);
于 2018-03-23T13:56:12.980 回答