Secret of the JavaScript Ninja 学习笔记 - 3

第三章 Functions are fundamental

3.2 Declarations

Function literal ::= function [funcName] (<parameters> ) { <statements> }

All functions have a property named name.


<!DOCTYPE html>
<html>
<head>
  <script type="text/javascript">
    /**
     * Declares a named function. The name is available throughout the current scope
     * and is implicitly added as a property of window
     */
    function isNimble() { return true; }
    
    /**
     * Creates an anonymous function that's assigned to the variable canFly. The variable 
     * is a window property and the name property of the function is empty
     */
    var canFly = function() { return true; }
    
    /**
     * Creates an anonymous function referenced by property of window
     */
    window.isDeadly = function() { return true; }

    /**
     * Defines an inner function inside the outer function That inner()
     * is able to be referenced before and after its declaration and that no global name is created for inner()
     */
    function outer() {
      inner();
      function inner() { print "inner"; }
      inner();
      window.inner === undefined;
    }
    outer();
    
    /**
     * The variable that we assign a function to has nothing to do with its name. That's
     * controlled by what we actually name the function in its literal
     */
    window.wieldSword = function swingWord() { return true; };
    window.wieldSword.name === "swingWord";
  </script>
</head>
<body>
</body>
</html>

Scoping and functions

In JavaScript, scopes are declared by functions, and not by blocks. 
if (window) {
  var x = 123;
}
alert(x);

a few nuances:
  • Variable declarations are in scope from their point of declaration to the end of the function within which they're declared, regardless of block nesting.
  • Named functions are in scope within the entire function within which they're declared, regardless of block nesting.
  • For the purposes of declaration scopes, the global context acts like one big function encompassing the code on the page.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值