JS中两个重要的方法 call & apply 学习

正题:

Function.prototype.apply(instance,args)  //args 数组

Function.prototype.Call(instance,a1,a2)  //a1,a2 单个参数

function People() {
            this.name = 'jinho';
            this.showName = function() {
          console.log(this);
          console.log(this.name); }; }
 function Student() {
            this.name = 'student';
        }

    

var p= new People(); //创建对象
var s= new Student(); //创建对象

p.showName();

输出:

p.showName.call(s);

输出:

说明showName函数的当前this已经变为p了,神奇之处来了! s对象本来没有showName()方法啊! 可以他还是执行了! 是由于call函数把 s 作为了 this!

p.showName.apply(s);

call函数和apply函数的区别是call 的语法是function.call(obj,param1,param2……);applay的语法是function.call(obj,[]/*params[]参数数组*/);

再附上我的同事evan给我讲解的一个例子:

function test(a,b) { 
console.log(this);
console.log(a); 
console.log(b); 
}

当调用test.call({},'1','2')时,前面的{}充当了test函数里的this,后面的1,2才是函数test的参数赋值

另外call和apply的用法只是在传参的时的形式不一样,如上例

原文地址:https://www.cnblogs.com/laneyfu/p/4371579.html