Why do we make an object constructor using this keyword and don't we simple write return { a: x, b:y} in the function? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 2

Why do we make an object constructor using this keyword and don't we simple write return { a: x, b:y} in the function?

So, when we make an object constructor we write: function example(x,y){ this.name = x; this.age = y; } var person = new example("John", 18); I understand how this works, new keyword creates a new object, this keyword creates the properties, wouldn't it however be easier to simple write: function example(x,y){ return {name: x, age: y}; } var person = example("John", 18);

27th Oct 2020, 5:27 PM
Karak10
Karak10 - avatar
1 Answer
+ 5
With return keyword, you store an object into person by calling the function. With this keyword and new keyword, you store an instance of a class into person. There is no difference up to this point. But for class, you can define class method Example.prototype.introduce = function(){ console.log(`Hi, I am ${this.name`} of ${this.age} year old.`); } That's called abstraction, or OOP.
27th Oct 2020, 5:54 PM
Gordon
Gordon - avatar