The front-end this points to the problem

Generally speaking:

1. Ordinary function: this points to the object that calls its function (for inheritance, etc., it is the principle of proximity, who is closest to who),

                     The so-called runtime binding.

2.call & apply & bind: You can change the this point, but after binding by the bind method,

                                     The function will always be bound to its first parameter object

3. window global method: this points to the window object (essentially a normal function, but the caller is window)

4. Constructor: this is the new object created

5.DOM event: this points to the element that triggered the event

6. Arrow function (=>): without its own this, it will use the this value of the context in which it is located (where it is defined) as its own this value, that is, it is often said to bind this when it is defined.

 

In the global environment:

this always points to the global object (window), whether in strict mode or not;

console.log(this === window); // true
this.a = 11;
console.log(window.a); // 11

 

Ordinary function:

this points to the object whose function was called

function f1(){
  return this;
}
function f2(){
  "use strict"; // this is strict mode
  return this;
}
var ss = {
  f1:function(){
    return this;
  },
  f2:function(){
    "use strict"; // this is strict mode
    return this;
  },
}

f1() === window; // true
f2() === undefined; // true
ss.f1() === ss; // true
ss.f2() === ss; // true

 

call & apply:

You can change this to point to

function f1(){
  return this.a;
}
var o = {a:33};
f1.call(o); //33
f1.apply(o); //33

 

window global method :

For example: alert, confirm, prompt, setTimeout, setInterval, onload, onresize, etc. this points to the window object

var tt = {
    a:'111',
    ff:function(){
        setTimeout(function() {
            console.log(this);
        }, 0);
    }
}
tt.ff(); //Window

 

 

Constructor:

this is the new object being created

function f1(){
  this.a = 22;
}
var o = new f1();
o.a === 22 //true

 

DOM events:

(1) When the code is included in the function to execute, similar to the ordinary function, this points to its caller;

(2) When processing directly, this points to the DOM element where it is located

<button onclick="console.log(this)">11111111111</button>
//结果:<button onclick="console.log(this)">11111111111</button>
<button onclick="(function(){console.log(this)})()">22222222222</button> //结果:Window
<button onclick="(function(){'use strict';console.log(this)})()">33333333333</button> //undefined

 

Arrow function:

to be continued. . .

 

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325838867&siteId=291194637