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. Hadoop下面WordCount运行详解

    单词计数是最简单也是最能体现MapReduce思想的程序之一,可以称为MapReduce版"Hello World",该程序的完整代码可以在Hadoop安装包的"src/ ...

  2. 基于openssl的单向和双向认证

    1.前言 最近工作涉及到https,需要修改nginx的openssl模块,引入keyless方案.关于keyless可以参考CloudFlare的官方博客: https://blog.cloudfl ...

  3. CentOS6.5菜鸟之旅:识别NTFS分区

    一.前言 CentOS默认时不能识别NTFS分区的,需要那么需要安装fuse-ntfs-3g来处理了. 二.安装fuse-ntfs-3g     yum install fuse-ntfs-3g

  4. Struts2文件上传(基于表单的文件上传)

    •Commons-FileUpload组件 –Commons是Apache开放源代码组织的一个Java子项目,其中的FileUpload是用来处理HTTP文件上传的子项目   •Commons-Fil ...

  5. 关于window.onload,window.onbeforeload与window.onunload

    ★  window.onload  当页面加载完毕的时候执行,即在当前页面进行其他操作之前执行.如,刚进入某个网页的弹窗提示. (  与window.onload相近的可以参考我写的另外一篇记录&qu ...

  6. ASP.NET使用UpdatePanel实现AJAX

    ScriptManager和UpdatePanel控件联合使用可以实现页面异步局部更新的效果.其中的UpdatePanel就是设置页面中异 步局部更新区域,它必须依赖于ScriptManager存在, ...

  7. [CLR via C#]15. 枚举类型和位标志

    一.枚举类型 枚举类型(enumerated types)定义了一组"符号名称/值"配对. 例如,以下Color类型定义了一组符号,每个符号都标识一种颜色: internal en ...

  8. [CLR via C#]13. 接口

    一.类和接口继承 在Microsoft.Net Framwork中,有一个名为System.Object的类,它定义了4个公共实例方法:ToString, Equals, GetHashCode和Ge ...

  9. WPF 中获取DataGrid 模板列中控件的对像

    WPF 中获取DataGrid 模板列中控件的对像 #region 当前选定行的TextBox获得焦点 /// <summary> /// 当前选定行的TextBox获得焦点 /// &l ...

  10. 记一次纠结Macbook 重装OS X的系统

    本文所有图片都是网上截图,不是实操环境.本文不具有教学意义. 起因:Macbook 白苹果了,无限菊花. 我的Macbook 只能装 OS X Mountain Lion 10.8,但是呢 MacBo ...