
深入了解 js 中 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.const button = document.getelementbyid("mybutton");
button.addeventlistener("click", function() {
console.log(this); // 输出:<!— dom element 'mybutton' —>
});const obj = {
name: "jane",
greet: () => {
console.log(`hello, my name is ${this.name}.`);
}
};
obj.greet(); // 输出:hello, my name is undefined.特殊情况
立即学习“Java免费学习笔记(深入)”;
const greeting = function() {
console.log(`Hello, my name is ${this.name}.`);
};
const boundGreeting = greeting.bind({ name: "Tom" });
boundGreeting(); // 输出:Hello, my name is Tom.这些用法只是 this 在 javascript 中众多用法中的一小部分。理解 this 的动态特性对于编写干净、可维护的代码至关重要。
以上就是JavaScript 中的 this:究竟指向哪里?的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号