程序开发 · 2024年2月12日

JavaScript 中的 this:究竟指向哪里?

深入了解 js 中 this 的用法

虽然文章提到 this 的值会根据函数调用方式而变化,但它有一个恒定的原则:this 始终指向调用函数的对象。但是,如果你想深入了解 this 的用法,请继续继续阅读。

this 的常见用法

  • 方法调用:函数作为某个对象的方法被调用时,this 指向该对象。例如:
const person = {
  name: "john",
  greet: function() {
    console.log(`hello, my name is ${this.name}.`);
  }
};

person.greet(); // 输出:hello, my name is john.

登录后复制

  • 事件处理程序:函数作为事件处理程序被调用时,this 指向触发事件的 dom 元素。例如:
const button = document.getelementbyid("mybutton");

button.addeventlistener("click", function() {
  console.log(this); // 输出:<!— dom element 'mybutton' —>
});

登录后复制

  • 箭头函数:箭头函数(=>)内部没有自己的 this,它会继承父中的 this。例如:
const obj = {
  name: "jane",
  greet: () => {
    console.log(`hello, my name is ${this.name}.`);
  }
};

obj.greet(); // 输出:hello, my name is undefined.

登录后复制

特殊情况

立即学习“”;

  • bind() 方法:可以手动将特定的对象绑定为函数的 this。例如:
const greeting = function() {
  console.log(`Hello, my name is ${this.name}.`);
};

const boundGreeting = greeting.bind({ name: "Tom" });

boundGreeting(); // 输出:Hello, my name is Tom.

登录后复制

  • apply() 和 call() 方法:类似于 bind() 方法,它们可以手动设置 this 的值。apply() 接受一个参数数组,而 call() 接受单个参数列表。

这些用法只是 this 在 javascript 中众多用法中的一小部分。理解 this 的动态特性对于编写干净、可维护的代码至关重要。

以上就是JavaScript 中的 this:究竟指向哪里?的详细内容,更多请关注GTHOST其它相关文章!