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里的INTERSECT

    在今天的文章里,我想讨论下SQL Server里的INTERSECT设置操作.INTERSECT设置操作彼此交叉2个记录集,返回2个集里列值一样的记录.下图演示了这个概念. INTERSECT与INN ...

  2. [Bootstrap]7天深入Bootstrap(1)入门准备

    由于申请了一个域名,一个云主机,开始弄个人网站. 发现Bootstrap非常方便,和重要,故开始学习与分享关于Bootstrap的技术. 推个广告 个人网站:http://www.neverc.cn ...

  3. AEAI ESB V3.5.4开源发布,应用集成平台

    AEAI ESB 应用集成平台为数通畅联的核心产品,本着分享传递的理念,数通畅联将ESB管理控制台项目开源,目的在于满足客户与伙伴的OEM需求,以及为广大IT爱好者的集成工具提供多一种选择,多一种便利 ...

  4. ExtJs特点、优缺点及注意事项

    摘自:ExtJs特点.优缺点及注意事项 1.什么是ExtJs?ExtJS可以用来开发RIA也即富客户端的AJAX应用,是一个用javascript写的,主要用于创建前端用户界面,是一个与后台技术无关的 ...

  5. jquery实现表格中点击相应行变色功能

    对于一个表格,为了使我们选中的项更容易区分,需要为选中项添加高亮,同时也需要,将其他项的高亮形式去除.类似于: <!DOCTYPE html> <html lang="en ...

  6. 重新想象 Windows 8 Store Apps (51) - 输入: 涂鸦板

    [源码下载] 重新想象 Windows 8 Store Apps (51) - 输入: 涂鸦板 作者:webabcd 介绍重新想象 Windows 8 Store Apps 之 涂鸦板 通过 Poin ...

  7. 线段树---Atlantis

    题目网址:http://acm.hust.edu.cn/vjudge/contest/view.action?cid=110064#problem/A Description There are se ...

  8. Dev-Cpp配置OpenGL图形库(成功版本:Dev-Cpp 5.7.1 MinGW 4.8.1)

    ★配置前须知:Dev-Cpp自带OpenGL的使用和OpenGL简介 (附Dev-Cpp下载地址:http://sourceforge.net/projects/orwelldevcpp/?sourc ...

  9. JSONArray.toCollection 封装 bean 失败

    1. 问题描述: 通过http请求服务端, 返回的bean的集合的字符串形式, 其中bean中的Date类型的属性值,形式为Long类型的表示形式(1466083519000): String res ...

  10. 获取用户的真实ip

    常见的坑有两个: 一.获取的是内网的ip地址.在nginx作为反向代理层的架构中,转发请求到php,java等应用容器上.结果php获取的是nginx代理服务器的ip,表现为一个内网的地址.php获取 ...