You need to enable JavaScript to run this app. JS调用对象greet方法报this.getFullName不是函数错误如何修复
优惠活动
大模型
产品
解决方案
定价
更多

JS调用对象greet方法报this.getFullName不是函数错误如何修复

错误核心原因

你代码中定义对象方法时使用了箭头函数,而箭头函数不会创建自己的this上下文,它的this会继承自定义时外层作用域的this。这里对象字面量的外层作用域是全局上下文,this并不指向greetings实例,所以this.getFullName()自然找不到对应的方法,触发类型错误。

修复方案

把对象的方法替换为普通函数或者ES6对象方法简写即可,普通函数的this会在调用时动态绑定,当通过greetings.Greet()调用时,this会自动指向greetings对象:

let greetings = {
    fullName : "elham zeinodini",
    // 用ES6方法简写替换箭头函数
    getFullName() {
        return this.fullName;
    },
    // 同样替换Greet方法的箭头函数
    Greet(message) {
        console.log(`${message} ${this.getFullName()} !!`)
    }
}

console.log(greetings.fullName);
// 正常输出:elham zeinodini
greetings.Greet("Hello");
// 正常输出:Hello elham zeinodini !!

如果需要兼容旧版本JS,也可以写成完整的普通函数声明:

getFullName: function() {
  return this.fullName
},
Greet: function(message) {
  console.log(`${message} ${this.getFullName()} !!`)
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.12 19:42:01