event、this、 that 和 window

2023-03-16  本文已影响0人  malgee
function handleClick(event) {
  console.log('Event type:', event.type);
  console.log('Target element:', event.target);
  console.log('Mouse position:', event.clientX, event.clientY);
}

var person = {
  name: 'Alice',
  sayHello: function() {
    console.log('Hello, my name is', this.name);
  }
};

person.sayHello(); // Hello, my name is Alice

this 是一个在运行时确定的关键字,它通常指向当前执行上下文中的当前对象。在不同的执行上下文中,this 可以指向不同的对象。

var person = {
  name: 'Alice',
  sayHello: function() {
    var that = this;
    setTimeout(function() {
      console.log('Hello, my name is', that.name);
    }, 1000);
  }
};

person.sayHello(); // Hello, my name is Alice

由于setTimeout() 方法会创建一个新的执行上下文,如果不使用 that 来保存this,在内部函数中,this 的值将不再是对象person,而是全局对象或undefined,导致错误的结果。通过使用 that,可以在内部函数中访问 person 对象,并正确地打印出 "Hello, my name is Alice"。

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

它们都指向同一个对象,所以这个比较表达式的结果是 true

上一篇 下一篇

猜你喜欢

热点阅读