What is the difference between call(), apply() and bind()?

The meaning of call(), apply(), bind()

Change the context in which the function is executed, i.e., change this to point to;

Grammar:

Let’s start with a simple example:

Window function demo(){console.log(this); //this points to window} demo(); * /Copy the code

– [1.call () calls a function with a specified this value and one or more arguments given separately.]

Var obj1={name:" fn1 ", fn1:function(val1,val2) {console.log(this.name,val1,val2); }} var obj2={name:" ", fn2:function() {console.log(this.name); }} this. Obj1. Fn1. Call (obj2, 111222); // This points to obj2Copy the code

The – [2.apply () method uses a specified this value and the one given separatelyAn array of one or more parametersTo call a function. ]

Var obj1={name:" fn1 ", fn1:function(a,b) {console.log(this.name,a,b); }} var obj2={name:" ", fn2:function() {console.log(this.name); }} this. Obj1. Fn1. Apply (obj2, [123456]); // This points to obj2Copy the code

– [3. Bind () also changes this, but returns a new function that needs to be called again.]

Var obj1={name:" fn1 ", fn1:function(val) {console.log(this.name); }} var obj2={name:" ", fn2:function() {console.log(this.name); } } var newfn3=obj1.fn1.bind(obj2); // This points to obj2 newfn3();Copy the code