V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
推荐关注
Meteor
JSLint - a JavaScript code quality tool
jsFiddle
D3.js
WebStorm
推荐书目
JavaScript 权威指南第 5 版
Closure: The Definitive Guide
captainXxX
V2EX  ›  JavaScript

新手求助 ——关于 javascript var hoisting 和 function 的问题!

  •  
  •   captainXxX · 2016-11-02 12:51:58 +08:00 · 1712 次点击
    这是一个创建于 2738 天前的主题,其中的信息可能已经有所发展或是发生改变。

    '''javascript btn.onclick = test;

      var test = function() {
        // displayMessage('Your inbox is almost full — delete some mails', 'warning');
        displayMessage('Brian: Hi there, how are you today?','chat');
        displayMessage('Brian: Hi there, how are you today?');
      }
      
       function displayMessage(msgText, msgType){
          ......
      }
    

    '''

    Because vareiable declarations(and declarations in general) are processed before any code is executed, declaring a variable anywhere in the code is equivalent to declaring it at the top. 这是 MDN 上面的原话。。但是把 btn.onclick = test;挪到 test 变量定义的下面就正确了。这是为什么??? 还有一点: btn.onclick=functionName;这是对的 但是 btn.onclick=anonymousFunctionName{}就是错的。必须要加上括号。。 但是 The parentheses in this context are sometimes called the "function invocation operator" 这也是 MDN 上面的原话。这又是为什么????

    4 条回复    2016-11-05 17:59:22 +08:00
    fds
        1
    fds  
       2016-11-02 14:23:37 +08:00
    declaration 是指 声明,不是定义。声明会提升到前面。也就是说你的代码相当于:

    var test
    onclick = test // 此时值为 undefined
    test = function(){}
    fds
        2
    fds  
       2016-11-02 14:32:27 +08:00
    btn.onclick=anonymousFunctionName{} 这根本就不符合语法吧?{}是什么?
    你要是定义了匿名函数,比如
    var anonymousFunctionName = function(){}
    btn.onclick = anonymousFunctionName
    这肯定是可以的。那句英文是说如果你
    var anonymousFunctionName = function(){}
    btn.onclick = anonymousFunctionName()
    就不对了,因为你是调用了函数获得了返回值,而不是把函数本身传给了 onclick 。
    otakustay
        3
    otakustay  
       2016-11-02 16:55:26 +08:00
    变量的声明会上提,并不是变量的赋值会上提,这是 2 个过程

    所以当你执行 btn.onclick = test 的时候, test 处于“已经声明,未赋值”的状态,即 undefined
    MRwaite
        4
    MRwaite  
       2016-11-05 17:59:22 +08:00
    关键词:函数声明 && 函数表达式 && 匿名函数
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   969 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 25ms · UTC 18:24 · PVG 02:24 · LAX 11:24 · JFK 14:24
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.