js中call、apply、bind函式

qq小小布丁發表於2017-08-03

1、call

var foo = {
        user: "liyongfen",
        getUser: function(){
            console.log(this.user);
        }
    }
    var bar = foo.getUser;
    bar();//undefine
    foo.getUser();//liyongfen

this沒有指向foo中的user

var foo = {
        user: "liyongfen",
        getUser: function(a,b){
            console.log(a+b);
            console.log(this.user);
        }
    }
    var bar = foo.getUser;
    bar.call(foo,1,3);//4 liyongfen
    foo.getUser(5,6);//11 liyongfen

call第一個引數改變this的指向,後面的引數是對應getUser中引數

2、apply

var foo = {
        user: "liyongfen",
        getUser: function(a,b){
            console.log(a+b);
            console.log(this.user);
        }
    }
    var bar = foo.getUser;
    bar.call(foo,[1,3]);//4 liyongfen
    foo.getUser(5,6);//11 liyongfen

apply裡的第一個引數指定this的指向,第二個引數是陣列。當第一個引數為null時,this指向window,call也一樣

3、bind

var foo = {
        user: "liyongfen",
        getUser: function(a,b){
            console.log(this);
            console.log(a+b);
            console.log(this.user);
        }
    }
    var bar = foo.getUser;
    var c = bar.bind(foo);
    c(4,8);//foo函式 12 liyongfen

bind繫結this後沒有立即執行,到想要執行是,再呼叫

相關文章