美文网首页
event、this、 that 和 window

event、this、 that 和 window

作者: malgee | 来源:发表于2023-03-16 15:42 被阅读0次
  • event 代表当前触发的事件对象。它是一个 JavaScript原生对象,包含有关事件的信息,例如事件类型、目标元素、鼠标位置等。通过访问event 对象,可以获取和修改这些信息,例如:
function handleClick(event) {
  console.log('Event type:', event.type);
  console.log('Target element:', event.target);
  console.log('Mouse position:', event.clientX, event.clientY);
}

  • this 代表当前执行上下文中的当前对象。在不同的执行上下文中,this 可以指向不同的对象。例如,当你在对象方法中使用this 时,它将指向该对象,例如:
var person = {
  name: 'Alice',
  sayHello: function() {
    console.log('Hello, my name is', this.name);
  }
};

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

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

  • that 通常用作一个变量名,它是在函数作用域中保存 this 引用的一个常用技巧。这是因为在 JavaScript 中,this 的值会根据执行上下文的不同而改变,可能会导致一些意想不到的错误。通过使用 that 可以解决这个问题,例如:
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"。

  • window 是浏览器中的全局对象,它包含了浏览器中所有的全局属性和方法。在浏览器中,所有的 JavaScript 代码都运行在一个全局的上下文中,该上下文中的 this 默认指向window 对象。例如:
console.log(this === window); // true

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

相关文章

网友评论

      本文标题:event、this、 that 和 window

      本文链接:https://www.haomeiwen.com/subject/jmhdrdtx.html