Let’s get right to it:

let length = 10;
function fn(){
  return this.length+1
}
let obj = {
  length:5.test1:function(){
    return fn()
  }
}
obj.test2=fn;
console.log(obj.test1())// this refers to fn,
console.log(fn()===obj.test2())//false
Copy the code

If your answer is correct, then congratulations, you have mastered JS function this point; Don’t be discouraged if you don’t get it right. It means you need to do some more research.

This refers to the special note:

Speaking of pointing to this: The first thing to note is that this is undefined when a function is defined (except for the arrow function). The execution of this is undefined only when the function is executed. In most cases, this ends up referring to the object on which it was last called (except in special cases).

The binding rules for this are: new binding, hard binding (call, apply, bind), implicit binding, default binding rules; There are many articles detailing these rules; I would like to emphasize the following points:

  1. The object’s method is declared by the arrow function, in which case, unless otherwise specified, the object calls the method and this points to window (in non-strict mode).
var a=1;
const obj ={
  a:4.print:() = >{console.log(this.a)}
}
obj.print();/ / 1


var a= 5;
const obj = {
  a:6.print:() = >{console.log(this.a)}
}
obj.print.call({a:7})/ / 5

Copy the code

2. If the object’s method contains a nested function, this refers to window (in non-strict mode) unless the object calls the method.

var name = "window.name";
      var obj = {
          name : "obj.name".getName:function(){
              console.log(this.name);
              return function(){
                  console.log(this.name);
              }
          }
      }
 obj.getName()();  // "obj.name" "window.name"
Copy the code

Answer key:

The opening bit of code is particularly clever because it declares a length variable globally; If you’re not careful, you temporarily ignore the length property of a function or the length property of a windoe. This question is very likely to fall into the trap of the question;

  1. You need to understand that the length attribute of the function refers to the number of parameters, which means how many parameters must be passed; And note that the number of ⚠️ parameters does not include the number of remaining parameters, only the number of parameters before the first one has a default value.
  2. The window’s length property refers to the number of frames the window currently contains;

So when fn () is executed alone, this refers to window, and when no other frame is used, 1 is returned. Obj.test2(), this refers to Obj, so returns 6; The test1 method in obj is a nested function, so this in the nested function refers to the window, so obj.test1() returns 1.