Object literal

From Wikipedia, the free encyclopedia

In Computer Science, a literal is a notation for representing a fixed value in source code, eg string literal. In contrast to this, variables or constants are symbols that can take on one of a class of fixed values, the constant being constrained not to change. Literals are often used to initialize variables, eg

int a=1;
String s="cat";

Technically, a literal will be assigned a value at compile time, while a variable or constant will be assigned at runtime.

In some object-oriented languages (like ECMAScript, but not C++), also objects can be represented by literals. Methods of this object can be specified in the object literal using function literals. The brace notation below, which is also used for array literals, is typical for object literals:

{"cat","dog"}
{name:"cat",length:57}

[edit] In ECMAScript/JavaScript

In ECMAScript respectively its derivatives JavaScript and ActionScript an object with methods can be written using the object literal like this:

var newobj = {
  var1: true,
  var2: "very interesting",
  method1: function () {
    alert(this.var1)
  },
  method2: function () {
    alert(this.var2)
  }
}
newobj.method1();
newobj.method2();