apply、call
来源:互联网 发布:如何修改sql数据库名称 编辑:程序博客网 时间:2024/05/18 14:45
apply、call
在js中,call
和apply
都是为了改变某个函数运行时的上下文(context)而存在的,换句话说,就是为了改变函数体内部的this
指向。
js的一大特点是,函数存在定义时上下文
和运行时上下文
以及上下文是可以改变的
这样的概念。
function fruits(){}fruits.prototype = { color:'red', say:function(){console.log('my color is '+this.color);}}var apple = new fruits;apple.say(); //'my color is red'
如果我们有一个对象banner = {color:'yellow'}
,我们不想重新定义say
方法,那么我们可以通过call
或者apply
调用apple对象是say方法:
var banana = {color:'yellow'};apple.say.call(banana);//'my color is yellow'apple.say.apple(banana); //'my color is yellow'
所以可以看出,call
和apple
是为了动态改变this
而出现的,当一个对象没有某个方法(banana对象没有say方法),但是其他的对象有(apple对象有say方法),我们可以借助call
或者apply
调用其他对象的方法来操作。
apply、call的区别
对于apply、call二者而言,作用完全一样,只是接受参数的方式不太一样。
var func = function(arg1,arg2){}
可以通过如下方式来调用:
func.call(this,arg1,arg2);func.apply(this,[arg1,arg2]);
其中的this
是你想指定的上下文,它可以是任何一个js对象,call
需要把参数按顺序传递进去,而apply
则是把参数放在数组里。
在js中,某个函数的参数数量是不固定的,因此要说适用条件的画,当你的参数是明确知道数量时用call
;而不确定参数个人的时候用apply
,然后把参数push进数组。
当参数数量不确定时,函数内部也可以通过arguments
这个数组来遍历。
为了巩固加深记忆,下面列举一些常用方法:
1.数组之间的追加
var arr1 = [12,'foo',{name:'joe'},-2458];var arr2 = ['doe',555,100];Array.prototype.push.apply(arr1,arr2);//arr1的值为: [12,'foo',{name:'joe'},-2458,'doe',555,100]
2.获取数组中最大值和最小值
var numbers = [5,458,120];var maxNumbers = Math.max.apply(Math,numbers); //458maxNumbers = Math.max.call(Math,5,458,120); //458
number本身没有max方法,但Math有,我们可以借助call
或apply
使用其方法。
3.验证是否是数组(前提是toString()方法没有被重写过)
function isArray(obj){ return Object.prototype.toString.call(obj) === '[object Array]';}
深入理解运用apply、call
定义一个log方法,让它可以代理console.log
function log(msg){ console.log(msg);}log(1); //1log(2); //2
上面的方法在当传入的参数个人不确定时,就无效了。这个时候就可以考虑使用apply
。
function log(){ console.log.apply(console,arguments);};log(1);//1log(1,2);//1 2
- call apply
- call apply
- apply/call
- apply()/call()
- apply、call
- call apply
- call()、apply()
- Apply call
- call+apply
- call、apply
- prototype-apply and call
- call apply方法
- javascript call apply
- javascript apply vs call
- js call apply
- apply,call备忘
- this call apply
- javascript call() apply()
- The Knowledge of Linux-.-Day08
- python各种删除空格符号的方法汇总
- linux之tar命令使用总结
- javascript数组(五)
- 多种负载均衡算法及其 Java 代码实现
- apply、call
- 位运算求整数平均值
- 测试序列的特点
- 使用LayoutInflater应该注意的问题
- Ubuntu 14.04 LTS Apache2 设置虚拟主机
- Nginx负载均衡_1
- UI设计师不可不知的安卓屏幕知识-安卓100分享
- Ubuntu 安装和使用Docker容器
- 【python学习笔记(1)】配置环境变量