作者mrbigmouth (大嘴先生)
看板Ajax
标题Re: [问题] javascript 函数的提升
时间Thu May 12 16:37:16 2016
※ 引述《kisha024 (4545454554)》之铭言:
: 各位好
: 我是参考这里的资料
: http://fireqqtw.logdown.com/posts/258823-javascript-function-notes
: function one() {
: console.log('global one');
: }
: function two() {
: console.log('global two');
: }
: function hoistFun() {
: console.log(typeof one);
: console.log(typeof two);
: one();
: two();
: function one() {
: console.log('local one');
: }
: var two = function() {
: console.log('local two');
: }
: }
: ---------------------------------------------------------------------
: 我不懂的是 two这个函数不是在hoistFun()里面又被定义一次
: 为什麽console.log(typeof two); 结果却是undefined?
: 另一个问题是 底下这两种宣告方式 在使用上都是写 two();
: 那到底有什麽差别呢? 谢谢
: function two() {
: console.log('global two');
: }
: var two = function() {
: console.log('local two');
: }
两个问题其实是一个解答,
function two() {
}
这种直接以function开头的宣告语法是一个包含了「宣告」与「定义」的动作:
「宣告一个名称为two的function并定义其内容」
在系统进行hoisting的时候会被一口气提升到scope最前方。
var two = function() {
}
这段语法其实是「创建一个匿名function」「并将其位址指派给two变数」的分解动作
於是系统进行hoisting时候被提升的只有var two,
=指定运算式是不会被提升的。
所以你执行hoistFun()时log two会跑出undefined,
因为该匿名function尚未指给two变数
此外,匿名function没有名称,在系统debug时或Error stack里会以
(anonymous function)的方式显示,造成追溯code时的麻烦,
如果可以,尽可能给function一个名称是比较好的设计方式。
--
※ 发信站: 批踢踢实业坊(ptt.cc), 来自: 211.75.132.13
※ 文章网址: https://webptt.com/cn.aspx?n=bbs/Ajax/M.1463042239.A.79A.html