Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a method in object literal notation?

Tags:

javascript

I learned there are 2 types of creating objects. First: object literal notation and second: Object constructor. I have learned that there are also methods and functions, but I couldn't understand how to create a method in object literal notation? In object constructor I just write:

var bob = new Object();
bob.age = 30;
bob.setAge = function(newAge) {
  bob.age = newAge;
};

Can you please tell me how to do the same when writing object literal notation.

var bob = {
  age: 30
};
like image 228
Vato Avatar asked Jul 05 '13 10:07

Vato


People also ask

How do you create an object literal?

Create Object using Object Literal SyntaxDefine an object in the { } brackets with key:value pairs separated by a comma. The key would be the name of the property and the value will be a literal value or a function. Syntax: var <object-name> = { key1: value1, key2: value2,...};

What is object literal notation?

The Object literal notation is basically an array of key:value pairs, with a colon separating the keys and values, and a comma after every key:value pair, except for the last, just like a regular array. Values created with anonymous functions are methods of your object. Simple values are properties.

What is an object literal in JavaScript?

Object Literal. In plain English, an object literal is a comma-separated list of name-value pairs inside of curly braces. Those values can be properties and functions.

What is the difference between creating an object using literal notation and creating an object using a constructor?

The main difference here is what you can do with it. With the constructor function notation you create an object that can be instantiated into multiple instances (with the new keyword), while the literal notation delivers a single object, like a singleton.


1 Answers

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;
  }
};
like image 100
Denys Séguret Avatar answered Sep 28 '22 18:09

Denys Séguret