call 和 apply 都是为了改变某个函数运行时的 context 即上下文而存在的,换句话说,就是为了改变函数体内部 this 的指向。
call 和 apply二者的作用完全一样,只是接受参数的方式不太一样。
applyFunction.apply(obj,args)方法能接收两个参数:
obj:这个对象将代替Function类里this对象
args:这个是数组或类数组,apply方法把这个集合中的元素作为参数传递给被调用的函数。
call
call方法与apply方法的第一个参数是一样的,只不过第二个参数是一个参数列表。
在非严格模式下当我们第一个参数传递为null或undefined时,函数体内的this会指向默认的宿主对象,在浏览器中则是window。
var test = function(){
console.log(this===window);}test.apply(null);//truetest.call(undefined);//true用法
"劫持"别人的方法
此时foo中的logName方法将被bar引用 ,this指向了bar
var foo = {
name:"mingming", logName:function(){ console.log(this.name); }}var bar={ name:"xiaowang"};foo.logName.call(bar);//xiaowangfunction Animal(name){
this.name = name; this.showName = function(){ console.log(this.name); } } function Cat(name){
Animal.call(this, name); }var cat = new Cat("Black Cat");
cat.showName(); //Black Cat
原文:https://www.cnblogs.com/magichu/p/14900278.html