How to create a method in object literal notation?

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;
  }
};

Leave a Comment