JS常见面试题 -- this指向

在方法中,this 表示该方法所属的对象

const obj = {
    
    
  f() {
    
    
    console.log(this)
  }
}
obj.f()
// Object

如果单独使用,this 表示全局对象

console.log(this)
// Window

在函数中,this 表示全局对象

function f() {
    
    
  console.log(this)
}
f()
// Window

在函数中,在严格模式下,this 是未定义的(undefined)

function f() {
    
    
  "use strict"
  console.log(this)
}
f()
// undefined

在事件中,this 表示接收事件的元素

<button onclick="console.log(this)">点我</button>
// <button οnclick="console.log(this)">点我</button>

更改方法中的this

<button id="btn">点我</button>
<script>
  let Person = {
    
    
    f() {
    
    
      return this
    }
  }
  btn.onclick = function() {
    
    
    console.log(Person.f.call(this));
  }
</script>
// <button id="btn">点我</button>

构造函数中的this

function Person() {
    
    
  this.f = function() {
    
    
    console.log(this);
  }
}
let p = new Person()
p.f()
// Person

箭头函数中的this

箭头函数的 this 与最近的外层函数(作用域)的this指向一致,定义时所在的对象,而不是使用时所在的对象

function Timer() {
    
    
  this.s1 = 0;
  this.s2 = 0;

  // 箭头函数,this 指向 Timer() 函数
  setInterval(() => this.s1++, 1000);

  // 普通函数
  setInterval(function () {
    
    
    this.s2++;
  }, 1000);
}
let timer = new Timer();

setTimeout(() => console.log('s1: ', timer.s1), 3000);

setTimeout(() => console.log('s2: ', timer.s2), 3000);
// s1: 3
// s2: 0

//上面代码中,前者的this绑定定义时所在的作用域(即Timer函数),后者的this指向运行时所在的作用域(即全局对象)

猜你喜欢

转载自blog.csdn.net/weixin_44257930/article/details/108534717