Water Cooler v2 Water Cooler v2 - 1 month ago 6
Javascript Question

Declaring a property inside a constructor function

I strongly suspect that the error I am getting by running the code snippet listed below is because JavaScript doesn't allow properties to be declared inside of a constructor function, but I can't be sure.

var Person = function(firstName, lastName)
{
getName: function() {
return this.firstName + ' ' + this.lastName;
}
};

var person = new Person('Joe', 'Bloggs');

alert('Hello, ' + person.getName() + "!");

/*
Exception: SyntaxError: function statement requires a name
@Scratchpad/2:4
*/


Could you please confirm if my suspicion is correct? And if it is, then the way to add a property is:


  1. To either use the object literal syntax?

    var Person = function(firstName, lastName)
    {
    this.firstName = firstName;
    this.lastName = lastName;
    };

    var person = { // object literal
    getName: function() {

    return this.firstName + " " + this.lastName;
    }
    };

  2. Or, to add the property to the constructor function's prototype?

    var Person = function(firstName, ..) { ... }
    Person.prototype.getName = ...;


Answer

It would work like this:

var Person = function(firstName, lastName) {
  this.firstName = firstName;
  this.lastName = lastName;

  this.getName = function() {
    return this.firstName + ' ' + this.lastName;
  }
};

var person = new Person('Joe', 'Bloggs');

alert('Hello, ' + person.getName() + "!");

But as mentioned you should put in on the prototype, so the new objects are sharing a method.

Person.prototype.getName = function getName() { return this.firstName  " " + this.lastName;}

Maybe you go and take a look in TypeScript. It transpiles everything correct and you get a easier syntax. Then you would write it like this:

class Person {
    constructor(private firstName: string, private lastName: string) {}

    public getName(): string {
        return this.firstName + " " + this.lastName;
    }
}

Also you could also define a getter property (setter also works with set):

function Person(firstName, lastName) {
  this.firstName = firstName;
  this.lastName = lastName;
};

Object.defineProperty(Person.prototype, "name", {
    get : function () {
        return this.firstName + " " + this.lastName;
    }
});

var person = new Person('Joe', 'Bloggs');

alert('Hello, ' + person.name + "!");

Comments