+ 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);
1 Réponse
+ 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.