apply和call
这个之前没研究过,今天简单的看了一下。
命令 |
简单介绍 |
例子 |
apply |
将某个函数提供给另外一个对象使用,类似继承 |
提供的方法.apply(获取方法的对象, 参数); |
call |
改变函数中this指向的对象 |
方法.call(被this指向的目标, 传给方法的参数). |
共同点:两个都是函数对象的方法。
call的说明:(略微修改自他人的博客,博客链接下附)
关于用call来进行继承(同样改自某博客的例子)
博客链接:
https://blog.csdn.net/sunboy_2050/article/details/6592082
apply可以参照这个(我之前写的):
apply是函数对象(function Function(){})的prototype方法中的一个方法
可以通过console.dir(Function)来打印全部方法
又因为所有函数都继承于Function函数,因此,所有函数都继承了这个方法。
apply的功能是,函数借用。将函数借用给一个对象,帮助他实现函数所定义的逻辑的功能。
如例子:
function ab(x, y) { this.x = x; this.y = y; } ab.prototype.move = function (x, y) { this.x += x; this.y += y } var c = new ab(1, 1); console.log(c); c.move(2, 2) console.log(c); p = {x: 0, y: 0, z: 0} console.log(p); c.move.apply(p, [5, 5]) //在这步,ab的实例c将move方法提供给了p,参数是数组 console.log(p);
输出结果为:
ab {x: 1, y: 1}
ab {x: 3, y: 3}
Object {x: 0, y: 0, z: 0}
Object {x: 5, y: 5, z: 0}
注:如果c中没有y,那么在