The way this points to

① In normal functions, this points to window ② in constructors, this points to the created object ③ in method declarations, this points to the caller ④ In timers, this points to window ⑤ in events, // This refers to the event source //this refers to window function foo() {console.log(this.a)} var a = 1foo() //this refers to obj, const obj = {a: 2, foo: Foo} obj.foo() //this points to the new function, that is, c const c = new foo() // This points to the position where this function is defined. Function a() {return () => {return () => {console.log(this)}}}}Copy the code

Change the direction of this

1. Use the bind

var foo = { x: 3 } var bar = function(){ console.log(this.x); } bar(); // undefined var boundFunc = bar.bind(foo); // Bind this to the window to access foo boundFunc(); / / 3Copy the code

3. If (function(j) {})(I)

Bind, apply, call

Before we get to the differences, let’s summarize the similarities:

The similarity

Both are used to change the direction of the function’s this object. 2. The first argument is the object to which this refers. 3. You can use subsequent parameters to transfer parameters.

The difference between

1. Call, apply, and bind are used to change this, but call and apply execute the function when changing this, and bind returns a new boundFcuntion binding when changing this. This is why the above example includes a pair of parentheses () after bind.

Bind is a hard binding, and the boundFunction this pointer returned cannot be changed again by bind, apply, or call. The call/apply binding only applies to the current call, then disappears and must be tied again the next time it is used.

3. Call functions exactly the same as apply, except that the call method passes the function call parameters in hash form, whereas the apply method takes an array of parameters. In the case of passing arguments, Call performs better than Apply because Apply takes one more step to parse the array at execution.

Wx.say.bind (this) cannot be executed immediately, invalid, Bind (this,”aaa”,” BBB “) wx.say.call(this,”aaa”,” BBB “) run immediately wx.say.apply(this,[“aaa”,” BBB “]) run immediately

Write a call, the apply and bind

Function.prototype.myCall = function (ctx) { ctx = ctx || window; ctx.fn = this; let args = Array.from(arguments).slice(1); let res = ctx.fn(... args); delete ctx.fn; return res; }; Function.prototype.myApply = function (ctx) { ctx = ctx || window; ctx.fn = this; let args = Array.from(arguments[1]); let res = ctx.fn(... args); delete ctx.fn; return res; }; Function.prototype.myBind = function (ctx) { let args = Array.from(arguments).slice(1); let that = this; return function (... oargs) { return that.apply(ctx, [...args, ...oargs]); }; };Copy the code