美文网首页
关于apply call bind一点点想法

关于apply call bind一点点想法

作者: 赵BW | 来源:发表于2017-05-01 14:45 被阅读0次

这几天在看别人的代码的时候,发现大神把apply、call、bind,用的出神入化。感觉自己需要整理一波。今天把自己的心得,整理一下。持续更新。


  • 了解一个东西的第一步查手册。
    手册

apply

方法在指定 this值和参数的情况下调用某个函数

  • 例:

    var person = {
            name:'zhaobw'
    }
    var student = {
           name:'tom'
    }
    function Out(){
           console.log(this.name);
    }
    Out.apply(person);
    Out.apply(student);
    

call

方法在指定 this值和参数的情况下调用某个函数

  • var person = {
            name:'zhaobw'
    }
    var student = {
           name:'tom'
    }
    function Out(){
           console.log(this.name);
    }
    Out.call(person);
    Out.call(student);
    

问题来了,这两个方法功能不是一样的么?
是的,他们是一样的!有一点点区别,就是第二个参数

只有一个区别,就是call()方法接受的是若干个参数的列表,而apply()方法接受的是一个包含多个参数的数组。

bind

创建一个新的函数, 当被调用时,它的this关键字被设置为提供的值 ,在调用新函数时,提供任何一个给定的参数序列。

var person = {
  name:'zhaobw'
}
var student = {
  name:'tom'
}
function Out(){
  console.log(this.name);
}
var p1 = Out.bind(person);
var s1 = Out.bind(student);
p1();
s1();

三个函数进行对比
  • 都是用来改变函数的this对象的指向的;
  • 第一个参数都是this要指向的对象;
  • 都可以利用后续参数传参;
  • bind是返回对应函数,便于稍后调用,apply、call是立即调用;

概念都说了。举几个例子。


  • 选出一个数组最大的数字,利用了apply参数是数组的方便。
    var arr = [1,2,3,4,5,6,7];
    console.log(Math.max.apply(Math,arr));

  • 判断一个对象是不是数组
    function isArray(obj){
    return Object.prototype.toString.call(obj) === '[object Array]' ;
    }

  • 判断一个对象是不是数组
    console.log(asd instanceof Array);

相关文章

网友评论

      本文标题:关于apply call bind一点点想法

      本文链接:https://www.haomeiwen.com/subject/lrvftxtx.html