“This article has participated in the call for good writing activities, click to view: the back end, the big front end double track submission, 20,000 yuan prize pool waiting for you to challenge!”
Call, apply, and bind all change the reference to this in the same way: they all change the reference to this in the function context
Differences: Call and apply accept parameters in different ways. Bind: not run immediately. Apply and call are executed immediately.
Usage:
- call:
- Nonstrict mode
If no arguments are passed, or if the first argument is null or nudefined, this points to the window
let fn = function(a,b){ console.log(this,a,b); } let obj = {name:"obj"}; Fn. Call (obj, 1, 2); // this:obj a:1 b:2 fn. Call (1,2); // this:1 a:2 b:undefined fn.call(); // this:window a:undefined b:undefined fn.call(null); // this=window a=undefined b=undefined fn.call(undefined); // this=window a=undefined b=undefinedCopy the code
- Strict mode
This refers to whoever the first argument is, including null and undefined. If no argument is passed, this refers to undefined
"use strict" let fn = function(a,b){ console.log(this,a,b); } let obj = {name:"obj"}; Fn. Call (obj, 1, 2); // this:obj a:1 b:2 fn. Call (1,2); // this:1 a:2 b=undefined fn.call(); // this:undefined a:undefined b:undefined fn.call(null); // this:null a:undefined b:undefined fn.call(undefined); // this:undefined a:undefined b:undefinedCopy the code
- Apply: Basically the same as call, the only difference is that apply passes the parameters that need to be passed to FN into an array (or array of classes). Although it writes an array, it is equivalent to passing the parameters to FN one by one
fn.call(obj, 1, 2);
fn.apply(obj, [1, 2]);
Copy the code
-
Bind: The syntax is the same as that of call. The difference is that bind is not compatible with IE6 and ie8
fn.call(obj, 1, 2); Bind (obj, 1, 2); bind(obj, 1, 2); // Change this in fn, fn does not executeCopy the code
This is changed to obj, but is executed immediately upon binding, and undefined is returned by fn when the click event is triggered
document.onclick = fn.call(obj);
Copy the code
Bind will preprocess fn’s this to obj, which will not be executed until it is clicked
document.onclick = fn.bind(obj);
Copy the code