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. Java魔法堂:以Windows服务的形式运行Java程序

    一.前言 由于防止维护人员误操作关闭Java控制台程序,因此决定将其改造为以Windows服务的形式运行.弄了一个上午总算搞定了,下面记录下来,以供日后查阅. 二.Java Service Wrapp ...

  2. Enum Helper

    public static class EnumHelper { #region get /// <summary> /// 获得枚举类型所包含的全部项的列表 /// </summa ...

  3. 浅谈WeakHashMap

    Java WeakHashMap 到底Weak在哪里,它真的很弱吗?WeakHashMap 的适用场景是什么,使用时需要注意些什么?弱引用和强引用对Java GC有什么不同影响?本文将给出清晰而简洁的 ...

  4. Sprint回顾-0525

    1.回顾组织 主题:“我们下次怎么样才能更加认真对待?” 时间:设定为1小时. 参与者:整个团队. 场所:宿舍走廊. 秘书:团队队长秘书,筹备.记录.整理.   2.回顾流程    Sprint总结: ...

  5. JavaScript中经典方法

    jQuery()通过name名称获取当前name中value数组 /** 获取input中name属性相同的 value数组 */ function my_array_name(m){ var val ...

  6. Array 数组常用方法

    (1)基本的数组方法 1.join() Array.join()方法将数组中所有元素都转化为字符串并连接在一起,返回最后生成的字符串.可以自己指定分隔的符号,如果不指定,默认使用逗号 var arr ...

  7. 数论 - 欧拉函数的运用 --- poj 3090 : Visible Lattice Points

    Visible Lattice Points Time Limit: 1000MS   Memory Limit: 65536K Total Submissions: 5636   Accepted: ...

  8. 【C#】线程之Parallel

    在一些常见的编程情形中,使用任务也许能提升性能.为了简化变成,静态类System.Threading.Tasks.Parallel封装了这些常见的情形,它内部使用Task对象. Parallel.Fo ...

  9. C语言字符串匹配函数

    C语言字符串匹配函数,保存有需要时可以用: #include <stdio.h> #include <stdlib.h> #include <string.h> # ...

  10. Azure开发者任务之六:使用WCF Service Web Role

    在本文中,我们将会在local development fabric上创建一个WCF服务角色,然后在一个控制台应用程序中使用它. WCF服务角色可以让我们创建一个WCF服务,并且把它托管在Window ...