返回

JS this相关练习题解析:为你轻松解决this的概念和应用问题

前端

认识this

this是一个在JavaScript中经常被使用的,它表示当前执行代码的对象。this可以是window对象、document对象、元素对象等。在事件处理程序中,this通常是指触发该事件的元素。在方法中,this通常是指调用该方法的对象。

this在事件绑定中的应用

在JavaScript中,可以使用addEventListener()方法为元素绑定事件处理程序。当事件触发时,事件处理程序将被执行。在事件处理程序中,this通常是指触发该事件的元素。例如,以下代码为元素绑定一个click事件处理程序:

element.addEventListener("click", function() {
  console.log(this); // 输出触发该事件的元素
});

当用户点击该元素时,上面的事件处理程序将被执行。此时,this将是指向该元素的引用。

this在方法执行中的作用

在JavaScript中,可以使用点号(.)运算符来调用对象的属性或方法。当方法被调用时,方法中的this通常是指调用该方法的对象。例如,以下代码调用对象的方法:

object.method();

当上面的代码被执行时,方法中的this将是指向该对象的引用。

JS this相关练习题

  1. 在以下代码中,this是指什么?
document.addEventListener("click", function() {
  console.log(this);
});
  1. 在以下代码中,this是指什么?
const button = document.querySelector("button");
button.addEventListener("click", function() {
  console.log(this);
});
  1. 在以下代码中,this是指什么?
class Person {
  constructor(name) {
    this.name = name;
  }

  greet() {
    console.log(`Hello, my name is ${this.name}.`);
  }
}

const person = new Person("John");
person.greet();
  1. 在以下代码中,this是指什么?
function greet() {
  console.log(`Hello, my name is ${this.name}.`);
}

const person = {
  name: "John",
  greet: greet
};

person.greet();
  1. 在以下代码中,this是指什么?
const button = document.querySelector("button");
button.addEventListener("click", greet);

function greet() {
  console.log(`Hello, my name is ${this.name}.`);
}

练习题答案

  1. this是指document对象。
  2. this是指button元素。
  3. this是指person对象。
  4. this是指person对象。
  5. this是指window对象。