Water Cooler v2
Water Cooler v2

Reputation: 33850

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 = ...;
    

Upvotes: 0

Views: 60

Answers (2)

Stefan Rein
Stefan Rein

Reputation: 9062

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 + "!");

Upvotes: 1

Max Koretskyi
Max Koretskyi

Reputation: 105497

I think JavaScript treats this line:

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

as labeled function declarations. What you want is probably this:

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

Upvotes: 2

Related Questions