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

JavaScript类执行顺序:代码中undefined的来源解析求助

控制台输出中undefined的来源解析

首先看执行的代码:

class Department{   
 constructor(){     
  console.log('parent class')   
 } 
} 
class Employee extends Department{  
  constructor(){    
   super()     
   console.log('child constructor method')   
  }     
  findName(){       
   console.log('Vimal');   
  } 
} 
let E1 = new Employee(); console.log(E1.findName())

原因说明:

  • findName()方法内部仅执行了console.log('Vimal'),没有显式返回任何值。在JavaScript中,所有函数如果没有通过return语句指定返回值,默认都会返回undefined。
  • 代码最后一行是console.log(E1.findName()),这里先调用E1.findName()打印出"Vimal",然后console.log()会把findName()的返回值(也就是undefined)再打印一次,这就是你看到的最后一个输出。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.05 11:03:12