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
相关推荐
颜酱21 小时前
单调队列:滑动窗口极值问题的最优解(通用模板版)
javascript·后端·算法
恋猫de小郭1 天前
移动端开发稳了?AI 目前还无法取代客户端开发,小红书的论文告诉你数据
前端·flutter·ai编程
文心快码BaiduComate1 天前
百度云与光本位签署战略合作:用AI Agent 重构芯片研发流程
前端·人工智能·架构
闲云一鹤1 天前
nginx 快速入门教程 - 写给前端的你
前端·nginx·前端工程化
QCY1 天前
「完全理解」1 分钟实现自己的 Coding Agent
前端·agent·claude
一拳不是超人1 天前
Electron主窗口弹框被WebContentView遮挡?独立WebContentView弹框方案详解!
前端·javascript·electron
anyup1 天前
🔥2026最推荐的跨平台方案:H5/小程序/App/鸿蒙,一套代码搞定
前端·uni-app·harmonyos
雮尘1 天前
如何在非 Claude IDE (TARE、 Cursor、Antigravity 等)下使用 Agent Skills
前端·agent·ai编程
icebreaker1 天前
Weapp-vite:原生模式之外,多一种 Vue SFC 选择
前端·vue.js·微信小程序
icebreaker1 天前
重走 Vue 长征路 Weapp-vite:编译链路与 Wevu 运行时原理拆解
前端·vue.js·微信小程序