js改变this指向

1. 使用call()apply()方法

call()apply()方法都可以用来调用一个函数,并显式地设置this的值。它们之间的主要区别是call()方法接受一个参数列表,而apply()方法接受一个包含多个参数的数组。

复制代码
function greet(greeting, punctuation) {  
  console.log(greeting + ', ' + this.name + punctuation);  
}  
  
const person = {  
  name: 'John'  
};  
  
// 使用call  
greet.call(person, 'Hello', '!');  
// 输出: Hello, John!  
  
// 使用apply  
greet.apply(person, ['Hi', '.']);  
// 输出: Hi, John.

2. 使用箭头函数

箭头函数不绑定自己的this,它会捕获其所在上下文的this值作为自己的this值,并且这个绑定在函数创建时就完成了。

复制代码
const person = {  
  name: 'Jane',  
  greet: function() {  
    setTimeout(() => {  
      console.log(this.name); // this指向person对象  
    }, 1000);  
  }  
};  
  
person.greet(); // 输出: Jane

3. 使用bind()方法

bind()方法会创建一个新的函数,在bind()被调用时,这个新函数的this被指定为bind()的第一个参数,而其余参数将作为新函数的参数,供调用时使用。

复制代码
function greet(greeting, punctuation) {  
  console.log(greeting + ', ' + this.name + punctuation);  
}  
  
const person = {  
  name: 'Doe'  
};  
  
const greetDoe = greet.bind(person, 'Howdy', '!');  
greetDoe(); // 输出: Howdy, Doe!

4. 在构造函数中使用new关键字

当使用new关键字调用构造函数时,this会被绑定到新创建的对象上。

复制代码
function Person(name) {  
  this.name = name;  
  this.greet = function() {  
    console.log('Hello, ' + this.name);  
  };  
}  
  
const person = new Person('Alice');  
person.greet(); // 输出: Hello, Alice
相关推荐
代码中介商3 分钟前
C++ 类型转换深度解析:static_cast、dynamic_cast、const_cast、reinterpret_cast
开发语言·c++
青小莫6 分钟前
C++之string(OJ练习)
开发语言·c++·stl
freshman_y6 分钟前
一篇介绍C语言中二级指针和二维数组的文章
c语言·开发语言
-Marks-19 分钟前
【C++编程】STL简介 --- (是什么 | 版本发展历程 | 六大组件 | 重要性缺陷以及如何学习)
开发语言·c++·学习·stl·stl版本
HealthScience1 小时前
【Bib 2026】基因最新综述(有什么任务、benchmark、代表性模型)
android·开发语言·kotlin
wjs20241 小时前
CSS 网格元素
开发语言
ejinxian1 小时前
Rust GUI框架Azul与Electron、WebView2
前端·javascript·electron
Java小白笔记1 小时前
OpenClaw 实战方法论
java·开发语言·人工智能·ai·全文检索·ai编程·ai写作
CoderCodingNo1 小时前
【信奥业余科普】C++ 的奇妙之旅 | 12:程序的交互与加工——数据的输入与算术运算
开发语言·c++