gpt4 book ai didi

Typescript构造函数,这两种构造对象的方法是等价的吗?

转载 作者:行者123 更新时间:2023-12-02 03:38:23 25 4
gpt4 key购买 nike

这两种创建/初始化新对象的方式有什么区别吗?或者它们是相同的吗?一种方法比另一种更好吗?

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

最佳答案

您正在创建的类型存在差异。在第一种情况下,您将创建 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

如果该类具有私有(private)属性,则无法构建兼容的对象文字:

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

关于Typescript构造函数,这两种构造对象的方法是等价的吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49434523/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com