Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
215 views
in Technique[技术] by (71.8m points)

javascript - Difference between bind, apply and call method?

I was searching in stackoverflow and the web, could not get proper results or explanation siting difference between these three methods.

As far as i understand, they all do the same executing the function/method in different context.

var google = {  
    makeBeer : function(arg1,arg2){     
         alert([arg1, arg2]);        
    }    
}

google.makeBeer('water','soda');

This is my normal function of the google object. Now when i make use of call and bind method here, here is the output.

var google = {
    makeBeer: function (arg1, arg2) {
        alert([arg1, arg2]);
    }
}

google.makeBeer('water', 'soda');

function yahoo() {}

var yah = new yahoo();
google.makeBeer.call(yah, 'pepsi', 'coke');

function msn() {

}

var msn = new msn();
google.makeBeer.call(msn, 'sprite', 'limca');

I still don't see a purpose of doing this, i can go-ahead and call the google.makeBeer three times with different arguments.

Can anyone enlighten me more over this.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

apply and call are the same thing except one accepts the arguments to be passed to the function in array form the other in parameter form.

bind does the same thing as call or apply depending on the framework you are using but doesn't call the function right away instead it returns a new function with your parameters bound to this and when the function is called from a new scope or context, this will still remain whatever you bound to it. Binding also allows you to prevent your constructors from being "hacked" by apply or call since it will always use the binded parameters for this no matter what someone sends to attempt to override this via call or apply.

Here is an example:

function Profile(u) {
    this.user = u;
    this.getUser = function () {
        return this.user;
    };
}

function Profile2(u) {
    this.user = u;
    this.getUser = (function () {
        return this.user;
    });
}

function Profile3(u) {
    this.user = u;
    this.getUser = (function () {
        return this.user;
    });
}

var x = new Profile('guest');
var x2 = new Profile2('guest');
var x3 = new Profile3('guest');

alert(x.getUser.apply({
    user: 'Vinoth'
})); // Vinoth
alert(x2.getUser.call({
    user: 'Babu'
})); // babu
alert(x3.getUser.bind(x3).call({
    user: 'Nandan'
})); // Guest

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...