JavaScript Patterns 4.1 Functions Background
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的更多相关文章
- 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 ...
- JavaScript Patterns 6.5 Inheritance by Copying Properties
Shallow copy pattern function extend(parent, child) { var i; child = child || {}; for (i in parent) ...
- JavaScript Patterns 5.8 Chaining Pattern
Chaining Pattern - Call methods on an object one after the other without assigning the return values ...
- JavaScript Patterns 5.5 Sandbox Pattern
Drawbacks of the namespacing pattern • Reliance on a single global variable to be the application’s ...
- JavaScript Patterns 5.3 Private Properties and Methods
All object members are public in JavaScript. var myobj = { myprop : 1, getProp : function() { return ...
- JavaScript Patterns 4.10 Curry
Function Application apply() takes two parameters: the first one is an object to bind to this inside ...
- JavaScript Patterns 6.7 Borrowing Methods
Scenario You want to use just the methods you like, without inheriting all the other methods that yo ...
- JavaScript Patterns 6.6 Mix-ins
Loop through arguments and copy every property of every object passed to the function. And the resul ...
- JavaScript Patterns 6.4 Prototypal Inheritance
No classes involved; Objects inherit from other objects. Use an empty temporary constructor function ...
随机推荐
- 无锁数据结构(Lock-Free Data Structures)
一个星期前,我写了关于SQL Server里闩锁(Latches)和自旋锁(Spinlocks)的文章.2个同步原语(synchronization primitives)是用来保护SQL Serve ...
- log4j的一些问题
今天,在学习log4j的时候发现了一点问题,关于level的问题. log4j.rootLogger=error, console, file , fileerror log4j.logger.com ...
- 0422 Step2-FCFS调度
一.目的和要求 1. 实验目的 (1)加深对作业调度算法的理解: (2)进行程序设计的训练. 2.实验要求 用高级语言编写一个或多个作业调度的模拟程序. 单道批处理系统的作业调度程序.作业一投入运行, ...
- 使用Swift操作NSDate类型基础
时间类型是我们在处理业务的时候使用非常频繁的一个数据类型.下面我们看一下时间NSDate的基本使用方法. 1.比较大小 我比较擅长.NET,我们知道C#里面DateTime类型可以使用"&g ...
- JAVA - package与import解析(一)
一.为什么要引入package和import?这个问题和c++中引入命名空间是一样的,也是为了解决重名问题.java通过包机制来解决重名问题,也就相当于给重名的代码加一系列前缀,从而达到唯一标识的作用 ...
- php实现的IMEI限制的短信验证码发送类
php实现的IMEI限制的短信验证码发送类 <?php class Api_Sms{ const EXPIRE_SEC = 1800; // 过期时间间隔 const RESEND_SEC = ...
- 查询自己电脑的IP
1.怎样查询电脑的IP 1)运用dos命令 在运行窗体上输入cmd,进入dos命令窗体,输出ipconfig/all命令,找到自己的IP地址 上面所圈出的就是本机IP地址 2) 进入“网络和共享中心” ...
- jQuery使用ajaxStart()和ajaxStop()方法
ajaxStart()和ajaxStop()方法是绑定Ajax事件.ajaxStart()方法用于在Ajax请求发出前触发函数,ajaxStop()方法用于在Ajax请求完成后触发函数.它们的调用格式 ...
- 最全面的jdbcUtils,总有一种适合你
附加jar包,TxQueryRunner.java文件,dbconfig.properties配置文件(点击链接下载): http://files.cnblogs.com/files/xiaoming ...
- mysql 数据类型,字符集
数据类型 1,数值类型2,字符串类型3,日期和时间4,ENUM和SET5,几何数据类型 数据类型选项 unsigned 无负值 zerofill 数值显示有影响,会前置0来填充不 ...