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

JavaScript内部函数中this关键字失效问题求助

解决JavaScript内部函数中this指向问题

你的代码里,虽然用bind把practice函数的this绑定到了person,但内部的close函数是独立的函数调用,它的this并不会继承外层practice的this——在非严格模式下会指向全局对象,严格模式下为undefined,所以输出my hobby is undefined。

下面是几种可行的解决方案:

方案1:用变量保存外层this

通过将外层函数的this赋值给一个变量,让内部函数通过这个变量访问正确的上下文:

function practice() {
  let self = this; // 保存practice函数的this
  function close() {
    console.log(`my hobby is ${self.hobby}`);
  }
  return close();
}

let person = {
  hobby: "programming"
};

let binding = practice.bind(person);
binding();

方案2:使用箭头函数

箭头函数没有自己的this,它的this继承自定义时所在的外层作用域,直接复用practice函数的this:

function practice() {
  const close = () => {
    console.log(`my hobby is ${this.hobby}`);
  };
  return close();
}

let person = {
  hobby: "programming"
};

let binding = practice.bind(person);
binding();

方案3:显式绑定内部函数的this

调用close函数时,用call显式绑定当前的this:

function practice() {
  function close() {
    console.log(`my hobby is ${this.hobby}`);
  }
  return close.call(this); // 绑定this后调用close
}

let person = {
  hobby: "programming"
};

let binding = practice.bind(person);
binding();

内容的提问来源于stack exchange,提问作者ToYlet

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.04 00:56:08