Functions are first-class objects and they provide scope.

• Can be created dynamically at runtime, during the execution of the program

• Can be assigned to variables, can have their references copied to other variables, can be augmented, and, except for a few special cases, can be deleted

• Can be passed as arguments to other functions and can also be returned by other functions

• Can have their own properties and methods

// antipattern

// for demo purposes only

var add = new Function('a, b', 'return a + b');

add(1, 2); // returns 3 

Any variable defined with  var inside of a function is a local variable, invisible outside the function. Saying that curly braces don’t provide local scope means that if you define a variable with  var inside of an  if condition or inside of a  for or a while loop, that doesn’t mean the variable is local to that i for for.

Variable scope

It’s only local to the wrapping function, and if there’s no wrapping function, it becomes a global variable.

Disambiguation of Terminology

function expression/ anonymous function

// function expression, a.k.a. anonymous function

var add = function (a, b) {

    return a + b;

}; 

named function expression

// named function expression

var add = function add(a, b) {

    return a + b;

}; 

Note

The only difference is that the name property of the function object will be a blank string. The name property is an extension of the language (it’s not part of the ECMA standard) but widely available in many environments.

The name property is useful when using debuggers, such as Firebug, or when calling the same function recursively from itself.

function declarations

function foo() {

    // function body goes here

}

Declarations Versus Expressions: Names and Hoisting

// this is a function expression, passed as an argument to the function `callMe`

callMe(function () {

    // I am an unnamed function expression

    // also known as an anonymous function

});

// this is a named function expression

callMe(function me() {

    // I am a named function expression

    // and my name is "me"

});

// another function expression

var myobject = {

    say: function () {

        // I am a function expression

    }

}; 

Function  declarations can only appear in “program code,” meaning inside of the bodies of other functions or in the global space. Their definitions cannot be assigned to variables or properties, or appear in function invocations as parameters.

// global scope

function foo() {}

function local() {

    // local scope

    function bar() {}

    return bar;

} 

Function’s name Property

The availability of the read-only  name property.

function foo() {} // declaration

var bar = function () {}; // expression

var baz = function baz() {}; // named expression

foo.name; // "foo"

bar.name; // "" // undefined in IE; empty string in FF, Webkit

baz.name; // "baz"

The case against function declarations and the reason to prefer function expressions is that the expressions highlight that functions are objects like all other objects and not some special language construct.

Note

Don't assign a different name to a named function expression since it's not properly implemented in some browsers(IE).

var foo = function bar() {};

Function Hoisting

// antipattern

// for illustration only

// global functions

function foo() {

    alert('global foo');

}

function bar() {

    alert('global bar');

}

function hoistMe() {

    console.log(typeof foo); // "function"

    console.log(typeof bar); // "undefined"

    foo(); // "local foo"

    bar(); // TypeError: bar is not a function

    // function declaration:
// variable 'foo' and its implementation both get hoisted
function foo() {
alert('local foo');
} // function expression:
// only variable 'bar' gets hoisted
// not the implementation
var bar = function () {
alert('local bar');
}; } hoistMe();

Just like with normal variables, the mere presence of foo and  bar anywhere in the hoistMe() function moves them to the top, overwriting the global foo and bar. The difference is that local  foo()’s  definition is hoisted to the top and works fine; although it’s defined later. The definition of bar()is not hoisted, only its  declaration.  That’s  why  until  the  code  execution  reaches  bar()’s  definition,  it’s undefined and not usable as a function (while still preventing the global  bar()from being “seen” in the scope chain).

JavaScript Patterns 4.1 Functions Background的更多相关文章

  1. JavaScript Patterns 7.1 Singleton

    7.1 Singleton The idea of the singleton pattern is to have only one instance of a specific class. Th ...

  2. JavaScript Patterns 6.5 Inheritance by Copying Properties

    Shallow copy pattern function extend(parent, child) { var i; child = child || {}; for (i in parent) ...

  3. JavaScript Patterns 5.8 Chaining Pattern

    Chaining Pattern - Call methods on an object one after the other without assigning the return values ...

  4. JavaScript Patterns 5.5 Sandbox Pattern

    Drawbacks of the namespacing pattern • Reliance on a single global variable to be the application’s ...

  5. JavaScript Patterns 5.3 Private Properties and Methods

    All object members are public in JavaScript. var myobj = { myprop : 1, getProp : function() { return ...

  6. JavaScript Patterns 4.10 Curry

    Function Application apply() takes two parameters: the first one is an object to bind to this inside ...

  7. JavaScript Patterns 6.7 Borrowing Methods

    Scenario You want to use just the methods you like, without inheriting all the other methods that yo ...

  8. JavaScript Patterns 6.6 Mix-ins

    Loop through arguments and copy every property of every object passed to the function. And the resul ...

  9. JavaScript Patterns 6.4 Prototypal Inheritance

    No classes involved; Objects inherit from other objects. Use an empty temporary constructor function ...

随机推荐

  1. SQL Server中的事务日志管理(2/9):事务日志架构概述

    当一切正常时,没有必要特别留意什么是事务日志,它是如何工作的.你只要确保每个数据库都有正确的备份.当出现问题时,事务日志的理解对于采取修正操作是重要的,尤其在需要紧急恢复数据库到指定点时.这系列文章会 ...

  2. 使用WinDbg调试SQL Server——入门

    这篇文章我想探究下SQL Server里完全不同的领域:如果使用WinDbg(来自针对Windows的调试工具)调试SQL Server.在我们进入枯涩细节之前,我想详细解释下为什么选择这样晦涩的话题 ...

  3. 我也想聊聊 OAuth 2.0 —— 基本概念

    这是一篇待在草稿箱半年之久的文章 连我自己都不知道我的草稿箱有多少未发布的文章了.这应该是我在上一家公司未解散之前写的,记得当时是要做一个开发者中心,很不幸. 今天,打开草稿箱有种莫名的伤感,看到这个 ...

  4. MySQL如何查询两个日期之间的记录

    baidu出来的结果多是下面答案:<quote> MySQL中,如何查询两个日期之间的记录,日期所在字段的类型为datetime(0000-00-00 00:00:00) 解决方案: 直接 ...

  5. JavaScript对象字面量

    <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <m ...

  6. KMP算法 --- 深入理解next数组

    在KMP算法中有个数组,叫做前缀数组,也有的叫next数组. 每一个子串有一个固定的next数组,它记录着字符串匹配过程中失配情况下可以向前多跳几个字符. 当然它描述的也是子串的对称程度,程度越高,值 ...

  7. 11条javascript知识

    1.局部变量和全局变量 var操作符定义的变量将成为定义该变量作用域中的局部变量.这个局部变量会在函数退出后销毁.不同于其他语言,javaScript不存在块级作用域. 全局变量就是window对象的 ...

  8. C#验证身份证号码

    一.18位的身份证号码 如:130429####%%%%00781.1~6位为地区代码,其中1.2位数为各省级政府的代码,3.4位数为地.市级政府的代码,5.6位数为县.区级政府代码.如13(河北省) ...

  9. Python入门笔记(20):Python函数(3):关于lambda

    一.lambda函数 1.lambda函数基础: lambda函数也叫匿名函数,即,函数没有具体的名称,而用def创建的方法是有名称的.如下: """命名的foo函数&q ...

  10. 【Unity】13.1 场景视图中的GI可视化

    分类:Unity.C#.VS2015 创建日期:2016-05-19 一.简介 在场景视图中设计不同的场景内容时,可以根据需要勾选相关的渲染选项,以便让场景仅显示其中的一部分或者全部渲染效果. 在这些 ...