代码之家  ›  专栏  ›  技术社区  ›  Sai Avinash

在控制台中记录typescript对象时属性不可见

  •  0
  • Sai Avinash  · 技术社区  · 6 年前

    public class student
    {
    name:string ;
    }
    
    let s=new student();
    
    console.log(s); --> This gives empty object with no properties . This should actually give an object with all 
    

    let s=new student();
    s.name="Avinash"
    
    console.log(s); --> This gives an object with name property and its value 
    

    有人能帮我理解这种行为吗?

    3 回复  |  直到 6 年前
        1
  •  2
  •   Titian Cernicova-Dragomir    6 年前

    在typescript类上声明属性(如果没有初始化为任何属性)只是一个没有运行时行为的声明。我们只是告诉编译器允许该属性存在,这样我们就可以使用它(就像您在第二个示例中所做的那样)。

    public class student
    {
      name: string;
      lastName : string = ""
    }
    

    JS公司:

    var student = /** @class */ (function () {
        function student() {
            this.lastName = ""; // just the initialized property 
        }
        return student;
    }());
    

    如果希望始终显示属性,请将其指定为默认值(如果仅 undefined

    public class student
    {
      name: string =  undefined;
      lastName : string = ""
    }
    let s=new student();
    console.log(s); // now we have student {name: undefined, lastName: ""}
    
        2
  •  0
  •   cymruu    6 年前

    您只需定义类可以具有的属性。要用值初始化它,请使用构造函数方法

    class student {
        name: string;
        constructor(name: string) {
            this.name= message;
        }
    }
    
        3
  •  0
  •   WasiF    6 年前

    MongoDb 数据库。我在模型和模式中有不同的属性,所以 确保你有相同的属性