Usage and difference of js call(), apply(), bind()

Posted by mariocesar on Mon, 07 Mar 2022 10:46:41 +0100

1. call()

Syntax:
fun.call(thisArg,arg1,arg2,...)

  • fun: represents a function
  • If the object "this" and "this" are to point to the global object, then "this" and "this" are to point to the global object;
  • Starting from arg1, it is the parameter to be passed to fun.

characteristic:
fun.call(thisArg,arg1,arg2,...)

  1. The fun function will be called immediately;
  2. The call method changes the object context of a function from the initial context to a new object specified by thisArg. If the thisArg parameter is not provided, the Window object is used as thisArg;
  3. Pass arg1 and other parameters into the fun function and return the return value of the fun function.
function getSum(num1, num2) {
	console.log(this); // Window
	return num1 + num2;
}

const obj = {};

getSum.call(obj, 2, 3); // this point: Obj return: 5

2. apply()

Syntax:
fun.apply(thisArg,[arg1,arg2,...])

  • fun: represents a function
  • Thisarg: the object to which this refers. If it is null or undefined, it points to the window global object;
  • The parameter is an array.

characteristic:
fun.apply(thisArg,[arg1,arg2,...])

  1. The fun function will be called immediately;
  2. The apply method changes the object context of a function from the initial context to a new object specified by thisArg. If the thisArg parameter is not provided, the Window object is used as thisArg;
  3. Pass the array into the fun function and return the return value of the fun function.
function getSum(num1, num2) {
	console.log(this);// Window
	return num1 + num2;
}

const obj = {};

getSum.apply(obj, [1, 2]); // this point: Obj return: 3

3. bind()

Syntax:
fun.bind(thisArg,[arg1,arg2,...])

  • fun: represents a function
  • Thisarg: the object to which this refers. If it is null or undefined, it points to the window global object;
  • Starting from arg1, all parameters are to be passed to fun.

characteristic:
fun.bind(thisArg,arg1,arg2,...)

  1. The fun function will not be called immediately, and a new function with this specified will be returned;
  2. The bind method changes the object context of a function from the initial context to a new object specified by thisArg. If the thisArg parameter is not provided, the Window object is used as thisArg;
  3. Pass arg1 and other parameters into the fun function.
function getSum(num1, num2) {
	console.log(this); // Window
	return num1 + num2;
}

const obj = {};
const newFun = getSum.bind(obj, 1, 2); // Returns a new function that specifies this
newFun(); // 3

4. Application of call(), apply() and bind()

1. call()

call is often used to inherit, because there are no extensions before ES6, and the constructor is used to simulate inheritance.

The following example:
Son obtains the attributes in the Father by changing the point of this in the Father constructor to achieve the effect of inheritance. Son can also add its own additional attributes:

function Father(name, age) {
	this.name = name;
	this.age = age;
}

function Son(name, age, gender) {
	Father.call(this, name, age);
	this.gender = gender;
}

const son = new Son("Xiao Ming", 24, "male");
son.name; // Xiao Ming
son.age; // 24
2. apply()

apply is often used in array related operations because the parameters passed are arrays.
Get the maximum and minimum values in the array:

const arr = [1, 4, 7, -1];
Math.max.apply(Math, arr); // 7
Math.min.apply(Math, arr); // -1

Array merge:

const arr = [1, 2];
const arr1 = [3];
Array.prototype.push.apply(arr, arr1); // 3
conaole.log(arr); // [1, 2, 3]
3. bind()

If we want to change the internal this point of a function, but we don't need to call the function immediately, use bind:

<body>
    <button>click</button>
    <script>
	    let btn = document.querySelector("button");
	    btn.onclick = function() {
	        this.disabled = true; // Here this means btn
	        setTimeout(function() {
	            console.log(this); // Window this means here
	            this.disabled = false; // Therefore, the disabled of btn will always be true
	        }, 3000)
	    }
    </script>
</body>
-----------------------------------------------------
<body>
    <button>click</button>
    <script>
	    let btn = document.querySelector("button");
	    btn.onclick = function() {
	        this.disabled = true;
	        setTimeout(function() {
	            console.log(this); // btn
	            this.disabled = false;
	        }.bind(this), 3000) // this is outside the timer function, so it points to the button object btn.
	    }
    </script>
</body>

Topics: Javascript Front-end