2

Is there any difference between these two ways of creating/initializing a new object? Or are they the same? Is one method better than the other?

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
SirPaulMuaddib
  • 233
  • 2
  • 9
  • 3
    Possible duplicate of [What is the difference between \`new Object()\` and object literal notation?](https://stackoverflow.com/questions/4597926/what-is-the-difference-between-new-object-and-object-literal-notation) – jonrsharpe Mar 22 '18 at 17:09
  • "The author chose this answer as correct, but it is incomplete. Be aware there are differences between the two syntaxes when you get into memory allocation." This is brought up, so does one allocate memory while the other just does assignment? – SirPaulMuaddib Mar 22 '18 at 17:22
  • 2
    So? There are numerous other answers. You don't have to (and shouldn't) only read the accepted one, that's no guarantee that it's try. – jonrsharpe Mar 22 '18 at 17:24

1 Answers1

5

There is a difference in the type you are creating. In the first case you are createing an instance of Person, in the second you are creating an object that has the same shape as Person.

There are differences between the two, for example insanceof behaves differently.

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

Also if your class has methods, you would need to specify them when initializing with an object literal:

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

And if the class has privates you can't build a compatible object literal:

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 
Titian Cernicova-Dragomir
  • 230,986
  • 31
  • 415
  • 357