This is the 26th day of my participation in the August Text Challenge.More challenges in August
- Call /apply/bind can force a manual change to this in a function by calling /bind/apply, etc
- call [function].call([context],params1,params2,….) [function] = function (); [function] = function (); This refers to [context] and params1 and params2 are passed to the function, respectively
- Apply works the same as call, except that the parameters passed to the function require an array of situations passed to Apply
Func.call (); func.call(); func.call(); func.call(); func.call(null); func.call(undefined) func.call(11) Number
- bind [function].bind([context],params1,params2,….) Syntactically similar to call. Call /apply, however, does not apply the same way. Call /apply executes the current function immediately and changes the reference to this in the function. Bind, however, preprocesses the function by referring to this in [context]. Params is stored in advance, but the function is not executed
let body = document.body; let obj = { name:"obj" } function func(x,y){ console.log(this,x,y); } body.onclick = func; Body. Onclick = func(10,20); Bind the click event body.click = func.bind(obj,10,20); Body. Onclick = function anoymous (){func.call(obj,10,20)}Copy the code
Bind is a closed system that stores functions that need to be executed, changes to this, and parameters that need to be passed to the function in a context that can be used for subsequent use
Function.prototype.bind = function(context= window,... Params){bind let _this = this return function anonymous(... Inners){execute bind (bind this is the function to operate on), return an anonymous function to the event binding or something else, and when the event fires, _this.apply(context,params.concat(inners))}}Copy the code
The Call application requires methods that convert arrays of classes (index and length and interator iterable) but not instances of arrays (not with methods on array prototypes) to arrays
- Array.from(arguments);
- Let args = […arguments] based on the expansion operator
- let args = []; for(let i=0; i
- Slice in array does not pass anything, clone it
Array.prototype.slice = function slice(){ let args = []; for(let i=0; i<this.length; i++){ args.push(this[i]) } return args; }Copy the code
- [].slice.call(arguments);
- []. ForEach. Call (the arguments, the item = > {}) traversal