call方法和apply方法

1.call

语法

call([thisObj[,arg1[, arg2[, [,.argN]]]]])

参数

thisObj  可选项。将被用作当前对象的对象。

arg1,arg2, , argN  可选项。将被传递方法参数序列。

说明

call 方法可以用来代替另一个对象调用一个方法。call 方法可将一个函数的对象上下文从初始的上下文改变为由 thisObj 指定的新对象。如果没有提供 thisObj 参数,那么 Global 对象被用作 thisObj。

2.apply

语法

call([thisObj[,arg1[, arg2[, [,.argN]]]]])

参数

thisObj  可选项。将被用作当前对象的对象。

argument[] 数组,被传递方法参数

说明

apply与call的功能几乎一样,第一个参数意义都一样,只是第二个参数有点不同apply传入的是一个参数数组,也就是将多个参数组合成为一个数组传入,call从第二个参数开始,依次传值给调用函数的参数 

3.call方法和apply 方法的区别

相同点:两个方法产生的作用是完全一样的,都用来改变当前函数调用的对象。

不同点:调用的参数不同:

//下列三行代码作用相同
foo.call(this,arg1,arg2,arg3) == foo.apply(this, arguments)==this.foo(arg1, arg2, arg3)

4.call和apply方法的作用

call方法的作用

  1.修改this指向

  2.继承

//例1
    window.color = 'red';
    document.color = 'yellow';
    var s1 = {color: 'blue' };
    function changeColor(){
         console.log(this.color);
    }
    changeColor.call();         //red (默认传递参数为globalObj)
    changeColor.call(window);   //red
    changeColor.call(document); //yellow
    changeColor.call(this);     //red
    changeColor.call(s1);       //blue
//例2
    var Pet = {
        words : '...',
        speak : function (say) {
            console.log(say + ''+ this.words)
        }
    }
    Pet.speak('Speak'); // 结果:Speak...

    var Dog = {
        words:'Wang'
    }

    //将this的指向改变成了Dog
    Pet.speak.call(Dog, 'Speak'); //结果: SpeakWang
//例3
  function FriendA(name){
   this.name=name;
  this.say=function () {
   console.log('hello');
  }
  }
  function FriendB() {
   console.log(this);
  FriendA.call(this,'lucy');
  console.log(this);
  }

 例3控制台:

FriendB继承了FriendA的方法和属性

heroes never die!
原文地址:https://www.cnblogs.com/daiSir/p/11242543.html