This is the fourth day of my participation in Gwen Challenge

this

This is a keyword in the JavaScript language.

It is an object that is automatically generated inside the function body while the function is running and can only be used inside the function body. When a function is called, an active record (context) is created. This record contains information about where the function was called (call stack), how the function was called, the parameters passed in, and so on. This is used during function execution and has nothing to do with where the binding or function declaration is located, except how the function is called.

This binding rule

The default binding

Independent function calls that cannot use the default rules for other rules

function foo() {
    log(this.a)		
}

var a = 2

foo()	// window
Copy the code

Implicit binding

Whether the location of the call has context

function foo() {
    log(this.a)  
}

var obj = {
    a: 2.foo: foo
}

obj.foo()	// obj
Copy the code

When a function reference has a context, the implicit binding rule binds the this in the function call to the context object, or only the last layer in the chain of object attribute references is in effect at the calling point

According to the binding

function foo () {
    log(this.a)
}

var obj = {
    a: 2
}

foo.call(obj)	// obj
Copy the code

The new binding

Construct foo(…) with new A new object is constructed and bound to foo(…) Calling this

function foo(a) {
    this.a = a
}

var bar = new foo(2)

log(bar.a)	// bar
Copy the code

priority

New Binding > Show Binding > Implicit binding

The four steps performed by the new operation

  • Build a brand new object
  • The new object will be connected by [[prototype]]
  • This new object is bound to the function call’s this
  • If the function returns no other object, the function call in the new expression automatically returns the new object

Apply, bind, call

// Call the difference

// Apply can pass in only one parameter other than this to run the caller directly
Function.apply(obj[, argArray])

// The return value of the bind method is a function, and the call needs to be executed. Apply and call are immediate calls.
Function.bind(thisArg[, arg1[, arg2[, ...]]])

// Call can take multiple arguments other than this to run the caller directly
Function.call(obj[, param1[, param2[,... paramN]]]])Copy the code