You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

为何在类方法中调用普通函数hello时,其this返回window对象?

为什么hello函数返回window而非App对象?

你的疑问核心在于对普通函数this指向的理解偏差,下面拆解原因和解决方法:

问题根源:普通函数直接调用的this规则

普通函数在非严格模式下直接调用(既不是作为对象的方法调用,也没有通过call/apply/bind绑定this,更不是用new实例化)时,this会指向全局对象——在浏览器环境里就是window。

看你的代码:

a() {
  return hello() // 这里是直接调用hello,没有绑定任何上下文
}

虽然a方法里的this指向App实例,但hello是独立调用的,它的this并不会自动继承a方法的上下文,所以自然指向window。

解决方法:让hello的this指向App实例

有几种常用方式可以实现:

1. 用call/apply绑定上下文

在调用hello时,通过call把a方法里的this(也就是App实例)传递给hello:

function hello() {
  return this
}
class App {
  constructor() {};
  a() {
    return hello.call(this)
  }
}
console.log(new App().a()) // 现在返回App实例

2. 把hello改成箭头函数

箭头函数的this会继承外层作用域的this,这里外层是a方法,所以hello的this会指向App实例:

const hello = () => {
  return this
}
class App {
  constructor() {};
  a() {
    return hello()
  }
}
console.log(new App().a()) // 返回App实例

3. 将hello作为App类的方法

如果业务允许,也可以把hello定义为App类的方法,这样调用时this自然指向实例:

class App {
  constructor() {};
  hello() {
    return this
  }
  a() {
    return this.hello()
  }
}
console.log(new App().a()) // 返回App实例

内容的提问来源于stack exchange,提问作者Ghiath Al-Abbas

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.14 08:50:24