缘起 最近找了个兼职,写了一段node的typescript代码,虽然上次写node还是5年前,但因为使用的框架是midway,写的过程中,几乎没有碰到bug,很自然的感觉,就是spring的那一套,面向对象,依赖注入等,写web还是很方便的。 不过也由于这几年天天看和写java代码,写的时候,很容易就按照面向对象写起来,一切都是class,class的方法等,所以这也是bug的由来。 问题来龙去脉 业务bug简单描述 一个学校有n个老师,每个老师一门课程,期末的时候,老师会给学生打分,学生同时也是一个用户。 问题:在打分的过程中,为了方便,对学生对象list转换成了map,然后每个老师都会对学生的分数进行统计,然后再把统计结果返回给学生,这样就会导致学生的分数被覆盖。发现学生的成绩到最后都是一个老师打的。 复现代码 class User { Name: string; Age: number; } class Student extends User { Grade: number; } class Teacher { Name: string; Class: string; Students: Student[]; } const user1 = new User(); user1.Name = 'John'; user1.Age = 30; const user2 = new User(); user2.Name = 'Jane'; user2.Age = 25; const users = [user1, user2]; const teacher = new Teacher(); teacher.Name = 'Bob'; teacher.Class = '1A'; const teacher2 = new Teacher(); teacher2.