2

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?

efw
  • 449
  • 3
  • 16
  • `johnDoe.foo = 'bar';`. Also, while comma is not syntactically invalid, it is not good practice to end statements with it. Use a semicolon instead. – Patrick Roberts Nov 16 '18 at 21:44
  • Whether you need to use `this` depends on what exactly you mean by "later" and how that code will be called. – Bergi Nov 16 '18 at 22:16
  • Thanks Robert -- I swapped in semicolons. – efw Nov 16 '18 at 23:45

1 Answers1

1

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.

joshweir
  • 5,427
  • 3
  • 39
  • 59
  • Should note there are other ways to do it as well such as setter in constructor – charlietfl Nov 16 '18 at 21:53
  • 1
    Thanks for the answers. I'm new to OOP. I understand there are other patterns for creating objects, and good reasons for avoiding this one, but I just wanted to make sure I understood how it worked on its most basic level. – efw Nov 16 '18 at 23:42