How to create a method in object literal notation?

This is the way to solve this exercise using literal object creation method:

var setAge = function (newAge) {
  this.age = newAge;
};

var bob = new Object();
bob.age = 30;
bob.setAge = setAge;

var susan = {
    age: 25,
    setAge: setAge
}

susan.setAge(35);

Its nothing different and as easy as

var bob = {
    age:     30,
    setAge:  function( newAge ) {
        this.age = newAge;
    }
};

Alternatively, you can create a real setter function either by invoking Object.defineProperty() or as simple as

var bob = {
    age:       30,
    firstName: 'j',
    lastName:  'Andy',
    set setName( newName ) {
        var spl = newName.split( /\s+/ );
        this.firstName = spl[ 0 ];
        this.lastName  = spl[ 1 ];
    }
}

Where you could go like

bob.setName = "Thomas Cook";  // which sets firstName to "Thomas" and lastName to "Cook"

Syntactically, the change is very simple :

var bob = {
  age: 30,
  setAge: function (newAge) {
    bob.age = newAge;
  }
};

But as you can see, there's a problem : as in your code it uses the external bob variable so this wouldn't work if you change the value of the bob variable.

You can fix that with

var bob = {
  age: 30,
  setAge: function (newAge) {
    this.age = newAge;
  }
};

Note that at this point you should check whether what you need isn't, in fact, a class, which would bring some performance improvements if you have several instances.

Update: ECMAScript 6 now allows methods to be defined the same way regardless of whether they are in an object literal:

var bob = {
  age: 30,
  setAge (newAge) {
    this.age = newAge;
  }
};

The last code you posted is missing a comma. Also, you don't need a ';' after a function definition of an object's property. Like this:

var object2 = {
name: "Fred",
age: 28,
club: "Fluminense",
bio2: function (){
    console.log(this.name +" is "+ this.age + " years old and he is playing in "+             this.club);
    }
};

Tags:

Javascript