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
相关推荐
亿元程序员6 小时前
为什么Cocos都4.0了还有人用2.x?
前端
MomentYY6 小时前
AI 到底是“懂”,还是在“猜”?
前端·人工智能·ai编程
鹏毓网络科技6 小时前
Cursor Rules 文件配置实战:3 个隐藏参数让我每月少写 40% 样板代码
前端·github
没烦恼3016 小时前
无痕模式下 HTTP\-First 拦截引发的“页面刷新”误判
前端
文心快码BaiduComate6 小时前
从个人提效到组织提效:Comate辅助构建自我进化的AI研发系统
前端·程序员
hunterandroid7 小时前
Compose 状态管理:remember、rememberSaveable 与状态提升
前端
星栈7 小时前
Dioxus 接数据库最容易写歪的 3 个地方:sqlx + SQLite 怎么接才顺
前端·rust·前端框架
晴虹7 小时前
vue3-scroll-more:横向滚动条-元素或页签过多滚动显示处理的组件
前端·vue.js
代码搬运媛7 小时前
Claude 全栈开发专用 Rules 配置
前端
PedroQue997 小时前
uni-router v1.7.0重磅更新:守卫重定向自由掌控
前端·uni-app