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 ...
随机推荐
- Android 学习笔记之AndBase框架学习(一) 实现多功能标题栏
PS:Volley框架终于通过看源码的方式完成了所有的学习..开始学习AndBase...AndBase的源码实在是多的离谱...因此就不对所有的源码进行分析了... 学习内容: 1.使用AndBas ...
- 前端翻译:Promises/A+规范
原文地址:https://promisesaplus.com/ 本篇为原文翻译+个人理解,若有谬误请各位指正,谢谢. 尊重原创,转载请注明来自:http://www.cnblogs.com/fsjoh ...
- Spring基础——一个简单的例子
一.学习版本 spring-framework-4.0.0 二.导入 jar 包: 三.在类路径下创建 Spring Config 文件:ApplicationContext.xml <?xml ...
- 使用RazorEngine对ASP.NET MVC的Views进行UnitTest
有的时候我们需要对Razor最后生产的文本(HTML OR XML OR..)进行单元测试. 使用Nuget安装RazorEngine. 新建一个ASP.NET MVC项目,并且带有测试项目. 修改I ...
- nodejs+express+jade给我baby做个小相册
去年年底迎来了my little star.从此人生多了一个最重要的牵挂.生了宝宝全家人都太忙了.最近宝宝稍微大点了,终于有空可以研究下技术了.这是14年第一帖.废话不多了.开始吧 1.安装NTVS ...
- 【Win10】单元测试中捕获异步方法的指定异常
温馨提醒:本文需要知道什么是单元测试才能阅读. 在之前 WPF.ASP.NET 中,单元测试要捕捉指定异常,我们是通过 ExpectedExceptionAttribute 来实现的.如下图: 但是, ...
- 网狐6603手机棋牌游戏源码.rar
网狐6603手机棋牌游戏源码.rar 文件大小: 333 MB 发布一款手机棋牌游戏源码带教程文档! 仅供学习,下载后请务必在24小时内删除! 网狐6603手机棋牌游戏源码 链接:http://p ...
- Winform开发框架之客户关系管理系统(CRM)的开发总结系列3-客户分类和配置管理实现
我在本系列随笔的开始,介绍了CRM系统一个重要的客户分类的展示界面,其中包含了从字典中加载分类.从已有数据中加载分类.以及分组列表中加载分类等方式的实现,以及可以动态对这些节点进行配置,实现客户分类的 ...
- 若干道Swift面试题
1,说说你认识的Swift是什么?Swift是苹果于2014年WWDC(苹果开发者大会)发布的新开发语言,可与Objective-C共同运行于MAC OS和iOS平台,用于搭建基于苹果平台的应用程序. ...
- 【Asphyre引擎】发布了新版本V101
引擎简称还是PXL,但是这个P是Platform而不是Pascal. 修复了一些bug,增加了轻量级的随机数发生器,进一步完善了XML的解析. 不是很明白,为何把Pascal扩展库改成Platform ...