Reputation: 469
When creating an object constructor in Javascript, I understand that it's necessary to prepend property names with the 'this' keyword.
function funcConstruct(first,last,age) {
this.firstName = first;
this.lastName = last;
this.age = age;
this.fullNameAge = function() {
return this.lastName + ', ' + this.firstName + ', ' + this.age
};
};
var johnDoe = new funcConstruct('John', 'Doe', 52);
console.log(johnDoe.fullNameAge());
Doe, John, 52
If you wish to add additional properties to the object later, do you need to use the 'this' keyword, and if so, where does it go in the syntax?
Upvotes: 2
Views: 1918
Reputation: 5617
You can add additional properties after the fact:
function funcConstruct(first,last,age) {
this.firstName = first,
this.lastName = last,
this.age = age,
this.fullNameAge = function() {
return this.lastName + ', ' + this.firstName + ', ' + this.age
}
};
var johnDoe = new funcConstruct('John', 'Doe', 52);
johnDoe.foo = "bar";
You are using the function constructor pattern, but note that there are other javascript object encapsulation patterns you can use depending on your use case some are better than others. In my opinion, I would use the function constructor pattern only if I was using pre ES6, if using >=ES6 (ES2015) I would use a class, and only if I needed a bunch of instances of the object. Otherwise, I would rather use the revealing module pattern if only a single instance of the object is required. Use fun
No use re-inventing the wheel, the accepted answer and some other highly voted answers to this question give a good summary. This video explains some of the confusion around using this
in javascript and provides an opinion that it is probably best to avoid this
where possible.
Upvotes: 1