This points to the problem

1. Methods in objects

let names = 'lisi'
let obj = {
    names: 'zhangsan'.fn: function() {
        console.log('I am'.this.names)
    }
}
obj.fn()   //I am zhangsan
Copy the code

2. Event binding

  • Inline binding
<! -- This points to Window -->
<input type="button" value="ClickFun button" onclick="clickFun()">

<script>
    function clickFun() {
        console.log('clickFun'.this)}</script>

<! -- This refers to the current input Node -->
<input type="button" value="Button" onclick="console.log(this)">

Copy the code
  • Dynamic binding
<! -- This refers to the current input Node -->
<input type="button" value="Button" id="btn">

<script>
    const btn = document.getElementById('btn')
    btn.onclick = function() {
        console.log(this)}</script>

Copy the code
  • Event listeners
<! -- This refers to the current input Node -->
<input type="button" value="Button" id="btn">

<script>
    const btn = document.getElementById('btn')
    btn.addEventListener('click'.function() {
        console.log(this)})</script>
Copy the code

constructor

Execution steps:

  • Create a new empty object
  • Point this in the constructor to this object
  • Execute the code in the constructor to add attributes to the new object
  • Return a new object
// This points to a new object
function Pro() {
    this.x = '1'
    this.y = function() {}}const p = new Pro()
Copy the code

4. The timer

const obj = {
    fun: function() {
        console.log(this)}}setTimeout(obj.fun, 1000)      // this -> window
setTimeout('obj.fun()'.1000)    // this -> obj
Copy the code

5. Call () and apply() methods of function objects

Call (obj, arg1, arg2… argN)

Parameter description: obj: The object to which this refers arg1, arg2… ArgN: List of arguments separated by a comma

const lisi = {names: 'lisi'}
const zs = {names: 'zhangsan'}
function fn(age, gender) {
    console.log(this.names, age, gender)
}

// undefined 23
fn(23)
// Fix this in the fn function to the object zs
fn.call(zs, 32.'male')
Copy the code