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

JavaScript:如何在函数内调用实例对象方法并返回该对象?

函数内创建子类实例并返回的正确实现

首先是已定义的类代码:

// Task 1: Code a Person class
class Person {
    constructor(name = "Tom", age = 20, energy = 100) {
        this.name = name;
        this.age = age;
        this.energy = energy;
    }
    sleep() {
        this.energy += 10;
        console.log("Energy has increased, now it's ", this.energy);
    }
    doSomethinFun() {
        this.energy -= 10
        console.log("Energy has decreased, now it's ", this.energy);
    }
}

// Task 2: Code a Worker class
class Worker extends Person {
    constructor(name, age, energy, xp = 0, hourlyWage = 10) {
        super(name, age, energy);
        this.xp = xp;
        this.hourlyWage = hourlyWage;
    }
    goToWork() {
        this.xp += 10
        console.log("XP is now increased, now it's ", this.xp);
    }
}

问题分析

你遇到的ReferenceError: intern1 is not defined错误有两个核心原因:

  • intern1是intern函数内部的局部变量,函数外部无法访问它
  • 你写的return intern()是递归调用intern函数,而非返回创建好的实例对象

正确实现代码

修改后的intern函数需在内部完成实例化、方法调用和返回操作:

function intern() {
    // 创建符合要求属性的Worker实例
    const intern1 = new Worker("Bob", 21, 110, 0, 10);
    // 调用实例的goToWork方法
    intern1.goToWork();
    // 返回该实例对象
    return intern1;
}

// 测试调用示例
const myIntern = intern();
console.log(myIntern);

关键说明

  • 所有操作都在intern函数内部完成,确保intern1的作用域合法
  • 返回值是创建好的实例intern1,而非递归调用函数本身
  • 推荐用const替代var,更符合现代JavaScript的变量声明规范

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 19:40:30