【发布时间】:2019-11-06 12:58:55
【问题描述】:
我试图想象一下 javascript 和 php 如何处理嵌套函数。
重点是:
php:
b(); //CANNOT call b at this point because isn't defined yet
a(); //CAN call a at this point because the interpreter see the declar
b(); //ok now i can call b, because the interpreter see the declaration after a execution
function a(){
function b(){
echo "inner";
}
}
同时在 javascript 中:
b(); //CANNOT call b isn't defined yet
a(); //CAN call a at this point because the interpreter see the declar
function a(){
function b(){
console.log("inner");
}
}
a(); //ok now i can call a because is defined
b(); // **CANNOT** call b yet !!
为什么在 javascript 中即使执行了 a 也不能调用 b()?在什么 PHP 行为不同?
提前致谢!
【问题讨论】:
-
即使语法看起来相似,这两种语言也完全不同。 JS 是原型,与 PHP 有不同的作用域规则。
-
JavaScript 有严格的词法作用域。在函数内声明的任何符号都是该函数(及其词法后代)私有的。对于
let和const,这也适用于简单的块。
标签: javascript php function nested-function