JavaScript中call,apply,bind方法的总结。

前言

why?call,apply,bind干什么的?为何要学这个?chrome

通常用来指定this的环境,在没有学以前,一般会有这些问题。数组

var a = {
    user:"汪某",
    fn:function(){
        console.log(this.user);
    }
}
var b = a.fn;
b(); //undefined
复制代码

咱们是想打印对象a里面的user却打印出来undefined是怎么回事呢?若是咱们直接执行a.fn()是能够的。bash

var a = {
    user:"汪某",
    fn:function(){
        console.log(this.user);
    }
}
a.fn(); //汪某
复制代码

这里可以打印是由于,这里的this指向的是函数a,那为何上面的不指向a?app

虽然这种方法能够达到咱们的目的,可是有时候咱们不得不将这个对象保存到另外的一个变量中,那么就能够经过如下方法。函数

一、call()

var a = {
    user:"汪某",
    fn:function(){
        console.log(this.user); //汪某
    }
}
var b = a.fn;
b.call(a);
复制代码

经过在call方法,给第一个参数添加要把b添加到哪一个环境中,简单来讲,this就会指向那个对象。this

call方法除了第一个参数之外还能够添加多个参数,以下:spa

var a = {
    user:"汪某",
    fn:function(e1,e2){
        console.log(this.user); //汪某
        console.log(e1+e2); //3
    }
}
var b = a.fn;
b.call(a,1,2);
复制代码

二、apply()

apply方法和call方法有些类似,它也能够改变this的指向code

var a = {
    user:"汪某",
    fn:function(){
        console.log(this.user); //汪某
    }
}
var b = a.fn;
b.apply(a);
复制代码

一样apply也能够有多个参数,可是不一样的是,第二个参数必须是一个数组,以下:cdn

var a = {
    user:"汪某",
    fn:function(e1,e2){
        console.log(this.user); //汪某
        console.log(e1+e2); //11
    }
}
var b = a.fn;
b.apply(a,[10,1]);
复制代码

或者对象

var a = {
    user:"汪某",
    fn:function(e1,e2){
        console.log(this.user); //汪某
        console.log(e1+e2); //520
    }
}
var b = a.fn;
var arr = [500,20];
b.apply(a,arr);
复制代码

注意若是call和apply的第一个参数写的是null,那么this指向的是window对象

var a = {
    user:"汪某",
    fn:function(){
        console.log(this); //Window {external: Object, chrome: Object, document: document, a: Object, speechSynthesis: SpeechSynthesis…}
    }
}
var b = a.fn;
b.apply(null);
复制代码

三、bind()

bind方法和call、apply方法有些不一样,可是无论怎么说它们均可以用来改变this的指向。

先来讲说它们的不一样吧。

var a = {
    user:"汪某",
    fn:function(){
        console.log(this.user);
    }
}
var b = a.fn;
b.bind(a);
复制代码

咱们发现代码没有被打印,对,这就是bind和call、apply方法的不一样,实际上bind方法返回的是一个修改事后的函数。

var a = {
    user:"汪某",
    fn:function(){
        console.log(this.user);
    }
}
var b = a.fn;
var c = b.bind(a);
console.log(c); //function() { [native code] }
复制代码

那么咱们如今执行一下函数c看看,能不能打印出对象a里面的user

var a = {
    user:"汪某",
    fn:function(){
        console.log(this.user); //汪某
    }
}
var b = a.fn;
var c = b.bind(a);
c();
复制代码

ok,一样bind也能够有多个参数,而且参数能够执行的时候再次添加,可是要注意的是,参数是按照形参的顺序进行的。

var a = {
    user:"汪某",
    fn:function(e,d,f){
        console.log(this.user); //汪某
        console.log(e,d,f); //10 1 2
    }
}
var b = a.fn;
var c = b.bind(a,10);
c(1,2);
复制代码

总结

bind返回对应函数, 便于稍后调用; apply, call则是当即调用。

  • 对于call来讲是这样的
fun.call(xh,"汪某","杭州");
复制代码
  • 对于apply来讲是这样的
fun.apply(xh,["汪某","杭州"]);
复制代码
  • 那么bind怎么传参呢?它能够像call那样传参。
fun.bind(xh,"汪某","杭州")();
复制代码

可是因为bind返回的仍然是一个函数,因此咱们还能够在调用的时候再进行传参。

fun.bind(xh)("汪某","杭州");
复制代码
相关文章
相关标签/搜索