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

JavaScript中this关键字实现失效及tracey.assessment()调用报错问题求助

问题分析与解决方案

让我们一步步拆解你遇到的问题,以及如何让代码按预期工作:

为什么调用 tracey.assessment() 会报错?

首先,你定义了全局变量 assessment 来存储 family("happy") 返回的函数,但你并没有把这个函数挂载到 tracey 对象上。tracey 对象里只有 MemberName、age 和 DOB 三个属性,根本不存在 assessment 方法,所以直接调用 tracey.assessment() 会抛出 TypeError: tracey.assessment is not a function 的错误。

为什么 this.MemberName 取不到 "Tracey"?

你的内部函数 person 是一个普通函数,当它被直接调用时(比如你原来的 assessment()),非严格模式下 this 会指向全局对象(浏览器里是 window,Node.js 里是 global),严格模式下 this 是 undefined,自然取不到 tracey 里的 MemberName。


解决方案:让 this.MemberName 指向 "Tracey",同时修复调用错误

这里有几种简单的实现方式,你可以根据需求选择:

方法1:将函数挂载到 tracey 对象后调用

把 family 返回的函数赋值给 tracey 的 assessment 属性,这样调用时 this 会自动指向 tracey(因为函数作为对象方法调用时,this 指向调用它的对象):

function family(emotion) {
  return function person() {
    console.log( `The core emotion that ${ this.MemberName } displays is ${ emotion }` );
  };
}
var tracey = {
  MemberName: "Tracey",
  age: 0,
  DOB: "29 September 2021",
};
// 将函数挂载到tracey对象
tracey.assessment = family("happy");
// 现在可以正常调用
tracey.assessment();
// 输出:The core emotion that Tracey displays is happy

方法2:使用 bind() 强制绑定 this

如果你不想修改 tracey 对象,可以用 bind() 方法把 person 函数的 this 永久绑定到 tracey,之后直接调用即可:

function family(emotion) {
  return function person() {
    console.log( `The core emotion that ${ this.MemberName } displays is ${ emotion }` );
  };
}
var tracey = {
  MemberName: "Tracey",
  age: 0,
  DOB: "29 September 2021",
};
// 绑定this到tracey
var assessment = family("happy").bind(tracey);
// 直接调用
assessment();
// 输出:The core emotion that Tracey displays is happy

方法3:用箭头函数继承外层 this

箭头函数没有自己的 this,它的 this 会继承自外层作用域的 this。我们可以把内部的 person 改成箭头函数,然后调用 family 时用 call() 把 family 的 this 绑定到 tracey:

function family(emotion) {
  // 改成箭头函数
  return () => {
    console.log( `The core emotion that ${ this.MemberName } displays is ${ emotion }` );
  };
}
var tracey = {
  MemberName: "Tracey",
  age: 0,
  DOB: "29 September 2021",
};
// 调用family时绑定this到tracey
var assessment = family.call(tracey, "happy");
assessment();
// 输出:The core emotion that Tracey displays is happy

另外,注意你代码里的小拼写错误:display's 应该是 displays(不需要所有格),不过这不影响功能运行。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.30 04:32:33