作者kisha024 (4545454554)
看板Ajax
标题Re: [问题] javascript 函数的提升
时间Thu May 12 17:00:55 2016
※ 引述《mrbigmouth (大嘴先生)》之铭言:
: ※ 引述《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一个名称是比较好的设计方式。
谢谢 想再请问 您说的'尽可能给function一个名称是比较好的设计方式'是指第一种吗?
另一个问题是 第二种和第三种在使用上 都是写two() 那两者有什麽差别吗?
谢谢
第一种
function two() {
console.log('global two');
}
第二种
var two = function name() {
console.log('local two');
}
第三种
var two = function() {
console.log('local two');
}
--
※ 发信站: 批踢踢实业坊(ptt.cc), 来自: 140.127.81.14
※ 文章网址: https://webptt.com/cn.aspx?n=bbs/Ajax/M.1463043658.A.29A.html
1F:→ mygirl30229: 你列出的第二种方式并不正确 05/12 19:27
谢谢 我已经修改了 不知是否正确?
※ 编辑: kisha024 (140.127.81.14), 05/13/2016 15:26:59
2F:推 xxxx9659: '尽可能给function一个名称是比较好的设计方式' 05/23 02:17
3F:→ xxxx9659: 我猜是下面这种 05/23 02:17
4F:→ xxxx9659: var two = function two() { ... } 05/23 02:18