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

TypeScript中类的内联字段初始化与构造函数内初始化的执行顺序问题

TypeScript中类的内联字段初始化与构造函数内初始化的执行顺序问题

嘿,我来给你把这个问题讲明白!你自己做的测试其实已经藏着答案啦,咱们一步步拆解来看~

首先明确结论:TypeScript里类的内联字段初始化,是在构造函数的自定义代码执行之前完成的。

拿你写的代码举例:

class Point{
    x :number = 0;
    y: number = 0;
    constructor();
    constructor(x:number,y?:number) ;
    constructor(x?:number,y?:number) {
        if(typeof x =='number') this.x = x;
        if(typeof y =='number') this.y = y
    }
}

let p = new Point(1);
console.log(`${p.x} ${p.y}`);

当你创建new Point(1)时,执行顺序是这样的:

  1. 先执行内联初始化:把x设为0,y设为0;
  2. 再进入构造函数执行自定义逻辑:因为传入了x=1,所以把this.x覆盖成1,而y没有传值,保持之前的0;
  3. 最后输出结果就是1 0,完全符合这个顺序。

其实从TypeScript编译后的JavaScript代码也能看出来,编译器会自动把内联初始化的代码移到构造函数的最开头,比如上面的代码编译后大概是这样:

class Point {
    constructor(x, y) {
        // 内联初始化被移到了构造函数最前面
        this.x = 0;
        this.y = 0;
        // 原来构造函数里的逻辑
        if (typeof x === 'number') this.x = x;
        if (typeof y === 'number') this.y = y;
    }
}

这样是不是就一目了然了?不管你在构造函数里写什么逻辑,内联的字段赋值永远是先执行的。

备注:内容来源于stack exchange,提问作者LeoPkm2-1

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.16 09:55:27