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

C#开发者求助:无法从Serie对象访问关联的Season对象属性

问题解决:无法访问Season对象属性的原因及修复

核心问题是Season类的构造函数拼写错误:把constructor写成了contructor。

在JavaScript中,类的构造函数必须严格命名为constructor,拼写错误会导致该方法不会被当作构造函数执行。实例化Season对象时,number和episode属性根本没有被赋值,所以后续访问serie1.season.number这类属性时,会得到undefined。

修正后的完整代码

class Serie
 {
   constructor(title, season, year)
   {
     this.title = title;
     this.season = season;
     this.year = year;
   }
 }

class Season
{
  constructor(number, episode) // 修正拼写错误
  {
    this.number = number;
    this.episode = episode;
  }
}

class Episode
{
  constructor(title, duration, hasBeenWatched)
  {
    this.title = title;
    this.duration = duration;
    this.hasBeenWatched = hasBeenWatched;
  }
}

let episode1 = new Episode("I'am s**", 45, false);
let saison1 = new Season(1, episode1);
let serie1 = new Serie("The Story of Tau", saison1, 1999);

document.querySelector('#first-episode-info').innerText = `Série: ${serie1.title}
Saison: ${serie1.season.number} 
  1 ${serie1.season.episode.title}
          ${serie1.season.episode.duration} min
          ${serie1.season.episode.hasBeenWatched ? 'Already watched' : 'Not yet watched'}
${serie1.year}`;

额外提醒

JavaScript作为动态类型语言,不会像C#那样在编译阶段检查标识符拼写错误,这类问题只会在运行时暴露。写类时一定要注意构造函数的正确命名,避免这类低级错误。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 03:45:54