我有以下测试代码:
// 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
被调用。这种语言是否设计成这样?还是我只是误解了什么?
谢谢你的帮助。