Personal technical blog, wechat official account, video account and design portfolio of the blogger


Before the blogger went to suning headquarters for an interview share missed a “this pointer” interview question, sorted out as follows, asked two aspects.

Interested ape friends canClick here toCheck out previous interview shares.

Which cases does this refer to:

  • Global scopeorCommon functionThis points to the global object window in the self-execution
  • Event functionsInternal this points to the event source: Note that if the event function contains a normal function, the internal this still points to the window after the normal function has been executed
  • Object methodsWhen called, this points to the calling object

1. This in global scope/normal function

The this object is bound at runtime based on the execution environment of the function: in a global function, this refers to window; When a function is called as a method on an object, this equals that object.

// Global scope
console.log(this);   //Window

// Normal function
function fn(){
    console.log(this); //Window
}
Copy the code

2. This in the event function refers to the event source

3. When an object method is called, this points to the calling object

let obj = {
    name : "lanlan".fn : function(){
        console.log(this);
    },
    lacy: {name : "didi".fn : function(){
            let num = 10;
            console.log(this); }}}; obj.fn();//obj
obj.dudu.fn();   //lacy
Copy the code

4. When an instance of a class calls a function, this refers to the instance

class B {
  fn() {
    console.log(this)}}var b = new B()
var fun = b.fn
b.fn()  / / points to b
fun()  // undefined
Copy the code

Classes under ES6 internally default to strict mode, fun does not specify global objects as the default call objects

5, ES6 arrow function this

This in the arrow function always points to the function closest to this when the arrow function is defined, or to window if there is no closest function

The this of the arrow function is bound when the function is defined, not during execution. Simply put, when a function is defined, this inherits from the object that defines the function.

Supplement:

There are several differences between the arrow function and the normal function, which should be paid special attention to during development:

  • The arguments object is not bound, which means that an error will be reported when accessing the object inside the arrow function.
  • Cannot be used as a constructor, that is, you cannot create an instance with the keyword new;
  • By default, the prototype property is not created.
  • Cannot be used as a Generator() function and cannot use the yeild keyword.

Wechat Official Account: FrontendApe