Sunday 27 December 2020

Constructors and Object Literals

In C# we can combine constructors expecting parameters and Object literals without a problem, like this:


class Person
{
	public string Name {get; set;}
    
       public int Age{get; set;}

       public string Country {get; set;}
       
       public Person(string name, int age)
       {
       	this.Name = name;
       	this.Age = age;
       }
}


var p3 = new Person("Francois", 2)
            {
                Country = "France"
            };

However, the above contructor+literal is not possible in JavaScript. Hopefully, it's really simple to do something similar with Object.assign:


class Person{
	constructor(name, age){
		this.name = name;
		this.age = age;
	}
    
    doGreet(greeting){
		return `${greeting}, I'm ${this.name} and I am ${this.age}`;
	}
}

//Obviously this is not valid JavaScript syntax
//let p1 = new Person("Francois", 2){
//	country: "France"
//};


let p1 = Object.assign(new Person("Francois", 2), {country: "France"});

console.log(JSON.stringify(p1, null, "\t"));

//this is not OK, we miss the Person [[prototype]] (hence, the methods) in the resulting object.
//let p0 = {...new Person("Francois", 2), ...{country: "France"}};

Notice that in this case we have to use Object.assign rather than the Object spread operator (...), as we would be missing the Person [[prototype]] in the resulting object.

No comments:

Post a Comment