javascript 中 this 工作原理
问题: JavaScript 中的 this 关键字是如何工作的?
回答:
this 关键字在 JavaScript 中扮演着关键角色,它表示当前正在执行代码的上下文对象。其值取决于函数的调用方式和执行环境。
函数调用方式:
箭头函数:
箭头函数没有自己的 this,而是继承调用它的函数的 this。
执行环境:
使用示例:
普通函数:
<code class="js">function greet() {
console.log(this); // window
}
greet();</code>对象方法:
<code class="js">const person = {
name: "John",
greet() {
console.log(this.name); // John
}
};
person.greet();</code>回调函数:
<code class="js">const button = document.getElementById("btn");
button.addEventListener("click", function() {
console.log(this); // DOM 元素
});</code>箭头函数:
<code class="js">const obj = {
name: "Jane",
greet() {
const arrowGreet = () => {
console.log(this.name); // Jane
};
arrowGreet();
}
};
obj.greet();</code>以上就是js中this的工作原理的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号