这两种创建/初始化新对象的方法有什么区别吗?或者他们是一样的吗?一种方法比另一种更好吗?
class Person {
FirstName: string = "";
LastName: string = "";
constructor(FN: string, LN: string) {
this.FirstName = FN;
this.LastName = LN;
}
}
var P:Person;
var P = new Person("John", "Smith"); // METHOD #1
var P = {FirstName:"John", LastName:"Smith"}; // METHOD #2
答案 0 :(得分:3)
您正在创建的类型有所不同。在第一种情况下,您正在创建Person
的实例,在第二种情况下,您将创建一个与Person具有相同形状的对象。
两者之间存在差异,例如insanceof
表现不同。
var P1 = new Person("John", "Smith");
var P2 : Person = {FirstName:"John", LastName:"Smith"};
console.log(P1 instanceof Person) // true
console.log(P2 instanceof Person) // false
此外,如果您的类有方法,则需要在使用对象文字初始化时指定它们:
class Person {
FirstName: string = "";
LastName: string = "";
constructor(FN: string, LN: string) {
this.FirstName = FN;
this.LastName = LN;
}
fullName() { return this.LastName + this.FirstName; }
}
var P2: Person = { FirstName: "John", LastName: "Smith" }; // error fullName missing
var P3: Person = { FirstName: "John", LastName: "Smith", fullName: Person.prototype.fullName }; // ok
如果班级有私立,你就无法建立兼容的对象文字:
class Person {
FirstName: string = "";
LastName: string = "";
constructor(FN: string, LN: string) {
this.FirstName = FN;
this.LastName = LN;
}
private fullName;
}
var P2: Person = { FirstName: "John", LastName: "Smith" }; // error Property 'fullName' is missing in type
var P3: Person = { FirstName: "John", LastName: "Smith", fullName: ""}; // Property 'fullName' is private in type 'Person' but not in type