编写高质量JS代码的68个有效方法(五)
No.21、使用apply方法通过不同数量的参数调用函数
Tips:
- 使用apply方法自定一个可计算的参数数组来调用可变参数的函数
- 使用apply方法的第一个参数给可变参数的方法提供一个接收者
//示例:计算给定数据的最大值
function getMaxNum(){
var max = arguments[0];
for(var i = 1, len = arguments.length;i < len; i++){
if(max < arguments[i]){
max = arguments[i];
}
}
return max;
}
getMaxNum.apply(null,[1,3,4]);
该方法和call()方法功能基本类似,差别在于参数写法不一样。
No.22、使用arguments创建可变参数的函数
Tips:
- 使用隐式的arguments对象实现可变参数的函数
- 考虑对可变参数的函数提供一个额外的固定元数的版本,从而使用者无需借助apply方法。
每一个函数内部都有一个arguments对象包含所有传递的参数
function fun1(){
console.log(arguments);
}
fun1('1');
fun1(1,'2','str');
No.23、永远不要修改arguments的值
Tips:
- 永远不要修改arguments的值
- 使用[].slice.call(arguments)将arguments对象赋值到一个真正的数组中再进行修改
arguments看起来像是数组,但是它并不是标准的数组,所以不支持数组的原型方法
function fun1(nums){
var lastParam = arguments.pop(); //报错,undefined is not a function。
console.log(arguments);
}
fun1([1, 2, 3]);
正确的做法是,将arguments转换为真正的数组,再进行操作,代码如下:
function fun1(nums){
var argArr = [].slice.call(arguments);
var lastParam = argArr.pop();
console.log(arguments);
}
fun1([1, 2, 3]);
注意:永远不要修改arguments对象是更为安全的。
No.24、使用变量保存arguments的引用
Tips:
- 当引用arguments时当心函数嵌套层级
- 绑定一个明确作用域的引用到arguments变量,从而可以再嵌套的函数中引用它
首先,先来看一段代码的输出:
function fun1(){
var i = 0;
console.log(arguments);
return {
next:function(){
return arguments[i++];
}
}
}
var f = fun1(1,2,3,4);
console.log(f.next()); //猜猜是啥?
arguments是函数中的隐式变量,每个函数都会有这样的一个隐式对象。所以最后一个console的结果可想而知。所以遇到这种场景,是建议用变量保存arguments的引用,也能让嵌套函数正确的进行对象引用,正确代码如下:
function fun1(){
var i = 0;
var args = arguments;
return {
next:function(){
return args[i++];
}
}
}
var f = fun1(1,2,3,4);
console.log(f.next());
No.25、使用bind方法提取具有确定接收者的方法
Tips:
- 要注意,提取一个方法不会将方法的接收者绑定到该方法的对象上
- 当给高阶函数传递对象方法时,使用匿名函数在适当的接收者上调用该方法
- 使用bind方法创建绑定到适当接收者的函数
老规矩,看代码:(代码1)
var buffer = {
entries: [],
add: function(value){
this.entries.push(value);
},
concat: function(){
return this.entries.join('');
}
};
该代码在直接使用时是没有问题的,思考下,由于高阶函数将函数/方法作为变量传递,那么可以有如下用法:(代码2)
var arr = ['Jay', '.M', '.Hu'];
arr.forEach(buffer.add);
console.log(buffer.concat()); //思考下这个结果是什么?
以上代码在arr.forEach处已经报错,Cannot read property 'push' of undefined。因为这个时候的涉及到this的指向问题。我们可以改造下buffer代码,输出this让我们看看:(代码3)
var buffer = {
entries: [],
add: function(value){
console.log(this);
this.entries.push(value);
},
concat: function(){
return this.entries.join('');
}
};
从输出结果我们可以看到这个this,在(代码2)的执行环境中,指向的是window对象,所以导致了报错,那么如何避免这样的问题呢?针对forEach,我们有三个方法:(代码4)
//方式一,去掉this,直接用buffer对象引用
var buffer = {
entries: [],
add: function(value){
buffer.entries.push(value);
},
concat: function(){
return buffer.entries.join('');
}
};
//方式二,指定接收者,forEach方法提供,其他方法不一定提供
var arr = ['Jay', '.M', '.Hu'];
arr.forEach(buffer.add, buffer);
console.log(buffer.concat());
//方式三,通过用函数包装调用,来实现指定接收者
var arr = ['Jay', '.M', '.Hu'];
arr.forEach(function(s){
buffer.add(s);
});
console.log(buffer.concat());
针对这样的问题,ES5标准库中提供了一个bind()函数来实现这样的方法。只需要如下代码:
var arr = ['Jay', '.M', '.Hu'];
arr.forEach(buffer.add.bind(buffer));
console.log(buffer.concat());
该bind()函数,利用buffer.add.bind(buffer)创建了一个新函数而不是修改了buffer.add函数。新函数行为就像原来函数的行为,但它的接收者被重新指定了。所以调用bind方法是安全的,即使是一个可能在程序的其他部分被共享的函数。
*:first-child {
margin-top: 0 !important;
}
body>*:last-child {
margin-bottom: 0 !important;
}
/* BLOCKS
=============================================================================*/
p, blockquote, ul, ol, dl, table, pre {
margin: 15px 0;
}
/* HEADERS
=============================================================================*/
h1, h2, h3, h4, h5, h6 {
margin: 20px 0 10px;
padding: 0;
font-weight: bold;
-webkit-font-smoothing: antialiased;
}
h1 tt, h1 code, h2 tt, h2 code, h3 tt, h3 code, h4 tt, h4 code, h5 tt, h5 code, h6 tt, h6 code {
font-size: inherit;
}
h1 {
font-size: 28px;
color: #000;
}
h2 {
font-size: 24px;
border-bottom: 1px solid #ccc;
color: #000;
}
h3 {
font-size: 18px;
}
h4 {
font-size: 16px;
}
h5 {
font-size: 14px;
}
h6 {
color: #777;
font-size: 14px;
}
body>h2:first-child, body>h1:first-child, body>h1:first-child+h2, body>h3:first-child, body>h4:first-child, body>h5:first-child, body>h6:first-child {
margin-top: 0;
padding-top: 0;
}
a:first-child h1, a:first-child h2, a:first-child h3, a:first-child h4, a:first-child h5, a:first-child h6 {
margin-top: 0;
padding-top: 0;
}
h1+p, h2+p, h3+p, h4+p, h5+p, h6+p {
margin-top: 10px;
}
/* LINKS
=============================================================================*/
a {
color: #4183C4;
text-decoration: none;
}
a:hover {
text-decoration: underline;
}
/* LISTS
=============================================================================*/
ul, ol {
padding-left: 30px;
}
ul li > :first-child,
ol li > :first-child,
ul li ul:first-of-type,
ol li ol:first-of-type,
ul li ol:first-of-type,
ol li ul:first-of-type {
margin-top: 0px;
}
ul ul, ul ol, ol ol, ol ul {
margin-bottom: 0;
}
dl {
padding: 0;
}
dl dt {
font-size: 14px;
font-weight: bold;
font-style: italic;
padding: 0;
margin: 15px 0 5px;
}
dl dt:first-child {
padding: 0;
}
dl dt>:first-child {
margin-top: 0px;
}
dl dt>:last-child {
margin-bottom: 0px;
}
dl dd {
margin: 0 0 15px;
padding: 0 15px;
}
dl dd>:first-child {
margin-top: 0px;
}
dl dd>:last-child {
margin-bottom: 0px;
}
/* CODE
=============================================================================*/
pre, code, tt {
font-size: 12px;
font-family: Consolas, "Liberation Mono", Courier, monospace;
}
code, tt {
margin: 0 0px;
padding: 0px 0px;
white-space: nowrap;
border: 1px solid #eaeaea;
background-color: #f8f8f8;
border-radius: 3px;
}
pre>code {
margin: 0;
padding: 0;
white-space: pre;
border: none;
background: transparent;
}
pre {
background-color: #f8f8f8;
border: 1px solid #ccc;
font-size: 13px;
line-height: 19px;
overflow: auto;
padding: 6px 10px;
border-radius: 3px;
}
pre code, pre tt {
background-color: transparent;
border: none;
}
kbd {
-moz-border-bottom-colors: none;
-moz-border-left-colors: none;
-moz-border-right-colors: none;
-moz-border-top-colors: none;
background-color: #DDDDDD;
background-image: linear-gradient(#F1F1F1, #DDDDDD);
background-repeat: repeat-x;
border-color: #DDDDDD #CCCCCC #CCCCCC #DDDDDD;
border-image: none;
border-radius: 2px 2px 2px 2px;
border-style: solid;
border-width: 1px;
font-family: "Helvetica Neue",Helvetica,Arial,sans-serif;
line-height: 10px;
padding: 1px 4px;
}
/* QUOTES
=============================================================================*/
blockquote {
border-left: 4px solid #DDD;
padding: 0 15px;
color: #777;
}
blockquote>:first-child {
margin-top: 0px;
}
blockquote>:last-child {
margin-bottom: 0px;
}
/* HORIZONTAL RULES
=============================================================================*/
hr {
clear: both;
margin: 15px 0;
height: 0px;
overflow: hidden;
border: none;
background: transparent;
border-bottom: 4px solid #ddd;
padding: 0;
}
/* IMAGES
=============================================================================*/
img {
max-width: 100%
}
-->
编写高质量JS代码的68个有效方法(五)的更多相关文章
- 编写高质量JS代码的68个有效方法(八)
[20141227]编写高质量JS代码的68个有效方法(八) *:first-child { margin-top: 0 !important; } body>*:last-child { ma ...
- 编写高质量JS代码的68个有效方法(七)
[20141220]编写高质量JS代码的68个有效方法(七) *:first-child { margin-top: 0 !important; } body>*:last-child { ma ...
- 编写高质量JS代码的68个有效方法(六)
[20141213]编写高质量JS代码的68个有效方法(六) *:first-child { margin-top: 0 !important; } body>*:last-child { ma ...
- 编写高质量JS代码的68个有效方法(四)
[20141129]编写高质量JS代码的68个有效方法(四) *:first-child { margin-top: 0 !important; } body>*:last-child { ma ...
- 编写高质量JS代码的68个有效方法(三)
[20141030]编写高质量JS代码的68个有效方法(三) *:first-child { margin-top: 0 !important; } body>*:last-child { ma ...
- 编写高质量JS代码的68个有效方法(二)
[20141011]编写高质量JS代码的68个有效方法(二) *:first-child { margin-top: 0 !important; } body>*:last-child { ma ...
- JavaScript手札:《编写高质量JS代码的68个有效方法》(一)(1~5)
编写高质量JS代码的68个有效方法(一) *:first-child { margin-top: 0 !important; } body>*:last-child { margin-botto ...
- 编写高质量JS代码的68个有效方法(十三)
No.61.不要阻塞I/O事件队列 Tips: 异步API使用回调函数来延缓处理代价高昂的操作以避免阻塞主应用程序 JavaScript并发的接收事件,但会使用一个事件队列按序地处理事件处理程序 在应 ...
- 编写高质量JS代码的68个有效方法(十)
*:first-child { margin-top: 0 !important; } body>*:last-child { margin-bottom: 0 !important; } /* ...
- 编写高质量JS代码的68个有效方法(十一)
*:first-child { margin-top: 0 !important; } body>*:last-child { margin-bottom: 0 !important; } /* ...
随机推荐
- Leetcode 107 Binary Tree Level Order Traversal II 二叉树+BFS
题意是倒过来层次遍历二叉树 下面我介绍下BFS的基本框架,所有的BFS都是这样写的 struct Nodetype { int d;//层数即遍历深度 KeyType m;//相应的节点值 } que ...
- 虚拟机下samba简单安装配置
系统是Win7 虚拟机是CenterOS6.5 1.关闭防火墙以及关闭SELINUX的强制模式(重要): service iptables stop//关闭防火墙 setenforce 0 //关闭S ...
- JQ例子:旋转木马
使用JQ现实旋转木马超级简单,它看起来很复杂,动画好像很难实现,但其实不然. 效果图: <!DOCTYPE html> <html lang="en"> & ...
- Android调用浏览器打开网址遇到的问题
我自己的手机(一加一代,升级了氢OS),然后在点击游戏内一个"隐私政策"-- 需要打开一个网页,然后就crash了.出错的信息如下: 完全是看不出来,然后我单独写了一个demo来测 ...
- Lucene 4.X 倒排索引原理与实现: (1) 词典的设计
词典的格式设计 词典中所保存的信息主要是三部分: Term字符串 Term的统计信息,比如文档频率(Document Frequency) 倒排表的位置信息 其中Term字符串如何保存是一个很大的问题 ...
- 忘记hmailiserver邮件服务器后台登陆密码解决
进入后台进行hmailiserver的相关设置,发现登陆密码忘记了,如下图:
- GTD时间管理(2)---管理收集箱
通过上面一篇文章,相信大家对GTD收集有了原理大致的了解,如果大家对收集不是很了解,可以去看一下. 当我们收集到很多想法和事情之后,在晚会的时候必须要清空收集箱,否则收集箱会堆积如山,最终收集箱成了垃 ...
- 一种可以避免数据迁移的分库分表scale-out扩容方式
原文地址:http://jm-blog.aliapp.com/?p=590 目前绝大多数应用采取的两种分库分表规则 mod方式 dayofweek系列日期方式(所有星期1的数据在一个库/表,或所有?月 ...
- 机器学习基石--学习笔记02--Hard Dual SVM
背景 上一篇文章总结了linear hard SVM,解法很直观,直接从SVM的定义出发,经过等价变换,转成QP问题求解.这一讲,从另一个角度描述hard SVM的解法,不那么直观,但是可以避免fea ...
- IntelliJ IDEA + Maven创建Java Web项目
1. Maven简介 相对于传统的项目,Maven 下管理和构建的项目真的非常好用和简单,所以这里也强调下,尽量使用此类工具进行项目构建, 它可以管理项目的整个生命周期. 可以通过其命令做所有相关的工 ...