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?

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

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Should note there are other ways to do it as well such as setter in constructor
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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.