Sir*_*dib 2 constructor typescript
这两种创建/初始化新对象的方式有什么区别吗?或者他们是一样的?一种方法比另一种更好吗?
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
Run Code Online (Sandbox Code Playgroud)
您创建的类型有所不同。在第一种情况下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
Run Code Online (Sandbox Code Playgroud)
此外,如果您的类有方法,则需要在使用对象文字初始化时指定它们:
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
Run Code Online (Sandbox Code Playgroud)
如果该类具有私有属性,则无法构建兼容的对象字面量:
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
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
49 次 |
| 最近记录: |