
js中this的用法
如上所述,this的值根据函数的调用方式而变化,但始终表示调用函数的对象。那么,如何确定函数对应的对象呢?以下是一些常见的规则:
const obj = {
name: "john",
greet() {
console.log(`hello, ${this.name}!`);
}
};
obj.greet(); // 输出 "hello, john!"function greet() {
console.log(`hello, ${this.name}!`);
}
greet(); // 输出报错:this.name is undefinedfunction person(name) {
this.name = name;
}
const person = new person("jane");
console.log(person.name); // 输出 "jane"const person = {
name: "John"
};
function greet() {
console.log(`Hello, ${this.name}!`);
}
greet.call(person); // 输出 "Hello, John!"理解this的用法至关重要,因为它决定了函数内部对对象属性和方法的访问方式。
以上就是JavaScript 中的 `this` 指向谁?的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号