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 ...
随机推荐
- js-计时事件
JavaScript 一个设定的时间间隔之后来执行代码,称之为计时事件. 主要通过两个方法来实现: 1.setInterval() - 间隔指定的毫秒数不停地执行指定的代码. 2.se ...
- mac ERROR 2002 (HY000): Can't connect to local MySQL server through socket '/tmp/mysql.sock' (2)
好久不用mysql,今天突然想用的时候, mysql -uroot -p 直接报了下面的错误 ERROR 2002 (HY000): Can't connect to local MySQL serv ...
- [JS] JavaScript框架(1) jQuery
jQuery使用户能更方便地处理HTML(标准通用标记语言下的一个应用).events.实现动画效果,并且方便地为网站提供AJAX交互.jQuery还有一个比较大的优势是,它的文档说明很全,而且各种应 ...
- 利用DropDownList实现下拉
在视图的Model<Vo>里面我们需要使用IEnumerable来将别的列表的数据全部的转化为下拉列表.下面是关于在项目中实际的写法. 一:实现下拉属性列表的写法 通过使用Select ...
- UnityShader快速上手指南(三)
简介 这一篇还是一些基本的shader操作:裁剪.透明和法向量的应用 (纠结了很久写不写这些,因为代码很简单,主要是些概念上的东西) 先来看下大概的效果图:(从左到右依次是裁剪,透明,加了法向量的透明 ...
- 2016C#模拟谷歌Google登陆Gmail&Youtube小案例
之所以写这个,是因为本来想写一个Youtube刷评论的工具,把登录做出来了,后面就没继续做下去. 涉及到基本的HttpWatch的应用以及Fiddler的应用(Fd主要用来排查问题,通过对比 浏览器和 ...
- 解决打印机报错:操作无法完成(错误0x00000709)。
解决:操作无法完成(错误0x00000709).再次检查打印机名称,并确保打印机已连接到... 上午同时说,网络打印机打印不了,于是首先看一下打印服务器IP是不是给换了,结果没换. 接着尝试重新添加一 ...
- C#强力粉碎文件代码分享,升级中用到
360的文件粉碎机还是很强大的,在我们客户端winform升级的时候,必须将有些文件进行强力删除后下载更新,如果删除失败很有可能整个 程序就无法更新到最新的版本,所以这里参考了网上的资料整理了一个文件 ...
- PHP OAuth2 Server库
想找比较正宗的库,查了蛮久的.最后在 oauth官方站上,看到PHP版本的相关链接. 发现都是php 5.3版本以上的环境,基于命名空间的写法编写的. 访问下面这个页面,难得,发现文档给出了5.2版本 ...
- phpwind的rewrite重写原理
没有深入过pw,被人问到这方面的问题,搜索了一下,发现了一篇博文,但原博客已打不开. http://www.phpsoho.com/html/document/200608/1154750694.ht ...