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

TypeScript对象创建疑问:两种User成员声明的区别及构造函数调用问题

Ionic3/Angular5中两种变量声明的区别解析

嘿,作为刚接触Ionic3和Angular5的新手,咱们把这两个声明的区别和你关心的构造函数问题说清楚哈~

先看你给出的代码:

export class User { 
  name: string; 
  email: string; 
  constructor() { 
    console.log("I am in constructor") 
  } 
} 

@Injectable() 
export class AuthProvider { 
  currentUser: User; 
  currentUser1 = new User() 
}

两种声明的核心区别

  • currentUser: User:这只是TypeScript的类型注解,它的作用是告诉编译器「这个变量未来应该存储User类的实例」,但它并没有真正创建User对象。此时currentUser的默认值是undefined,因为你没有给它赋值。
  • currentUser1 = new User():这是「类型推断+实例化」的操作。TypeScript会自动推断currentUser1的类型是User,同时new User()会直接创建User类的实例,这时候就会触发User的构造函数,所以你能在控制台看到"I am in constructor"的输出。

关于构造函数调用的问题

用currentUser: User这种写法不会调用User类的默认构造函数,因为它只是给变量做了类型标记,没有执行任何实例化的逻辑。只有当你执行currentUser = new User()这样的赋值操作时,才会触发构造函数,创建真正的User实例。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.28 04:10:58