Comparison of apply call bind

Compared with apply, call, and bind, what are the similarities and differences? When to use apply, call, and when to use bind? Give a simple example:

var obj = {
    
    
    x : 81,
};
var foo = {
    
    
    getX: function () {
    
    
        return this.x;s
    }
};
console.log(foo.getX.bind(obj)()),
console.log(foo.getX.call(obj)),
console.log(foo.getX.apply(obj))

Print result:
Insert picture description here
all three outputs are 81, but pay attention to the use of bind() method, there are more parentheses after him.

In other words, the difference is that when you want to change the context, not immediately, but when the callback is executed, use the bind) method. And apply/call will execute the function immediately.

The difference between
apply and call For both apply and call, the effect is exactly the same, but the way of accepting parameters is different. For example, there is a function defined as follows:

    var func = fuction( arg1 , arg2 ) {
    
    

    };

transfer:

func.call( this , arg1 , arg2 );
func.apply( this, [ arg1 , arg2 ])

Summary:
apply. Call. Bind are used to change the direction of the this object of the function;
apply, call and bind the first parameter of the three is the object that this points to, that is, the context that you want to specify;
apply. Call. bind can use subsequent parameters to pass parameters;
bind returns the corresponding function, which is convenient for later calling; apply. call is called immediately.

There is an interesting question. If you bind() twice in a row, or bind() three times in a row, what is the output value? Like this:

    var bar = function(){
    
    
        console.log(this.x)
    }
    var foo = {
    
    
        x : 3
    }
    var sed = {
    
    
        x : 4
    }
    var func = bar.bind(foo).bind(sed)
    func()

    var fiv = {
    
    
        x : 5
    }
    var func = bar.bind(foo).bind(sed).bind(fiv)
    func()

The print result is as follows: The
Insert picture description here
answer is that both times will still output 3 instead of the expected 4 and 5. The reason is that in Javascript, multiple bind() is invalid. For deeper reasons, the realization of bind() is equivalent to using a function to wrap a call / apply internally. The second bind() is equivalent to wrapping the first bind(), so the bind after the second is Unable to take effect.

Guess you like

Origin blog.csdn.net/QZ9420/article/details/112383227