Object literals are using a specific notation invented for JavaScript that is called: "JSON = "Java Script Object Notation". This notation is nice and slim so it was adopted by many other programming languages as a data format.
A simplified version of JSON has become standard for storing objects in text files or sending objects over the network. It is considered a light weight data representation format. It can not transport functions though.
let person = {
firstName : "John",
lastName : "Doe",
age : 50,
eyeColor : "blue",
fullName : function () {
return this.firstName + " " + this.lastName
}
};
In this example we declare an object: person that has several properties and one method. A method is a property of type function. The method name in this example is fullName.
Observe:
You can access object members in two ways:
You access an object method with the following syntax:
objectName.methodName();
Inside methods you access properties of object using "this" keyword:
this.propertyName;
console.log(person.firstName); // John
console.log(person.lastName); // Doe
console.log(person.fullName());// John Doe
You can create an empty object using syntax:
// create empty object
const objectName = {};
// add properties
objectName.x = 10;
objectName.y = 20;
Note: This is just a demo, in practice you should not use this method to create objects. The code looks messy and is considered bad practice.
An object factory is a normal function that create an object. This kind of function is no longer used in practice but in older JavaScript code. It is good to know about this so you can read older code:
/* object factory function */
function createNewPerson(name) {
var obj = {};
obj.name = name;
obj.greeting = function() {
console.log('Hi! I\'m ' + obj.name + '.');
};
return obj;
}
/* create new objects */
var johnPerson = createNewPerson("John");
var petruPerson = createNewPerson("Petru");
johnPerson.greeting(); //call object method
petruPerson.greeting(); //call object method
This is a special function that can produce an object, using keyword "new". This function is more elegant than "object factory". Does not have return, and is used only to create object instances.
/* object constructor */
function Person(name) {
this.name = name;
this.greetings = function() {
console.log('Hi! I\'m ' + this.name + '.');
};
};
// instantiate two objects
var john = new Person("John");
var petru = new Person("Petru");
john.greetings(); // Hi! I'm John
petru.greetings();// Hi! I'm Petru
JavaScript has predefined objects. One of these is the "Fundamental Object". There are two alternative methods to create objects using the fundamental object:
// equivalent to "var o = {}";
let o = new Object();
// equivalent to "b = new Boolean()";
let b = new Object(Boolean());
Object.create() method can be used to create new object from an existing object. The new object is based on "object prototype". An object prototype is automatically created when you create the object.
By reusing a prototype you inherit all its methods. This is how inheritance works in JavaScript. Therefore JavaScript is a Prototype Oriented Language. You can access the prototype using dot notation and you can extend the prototype with new functions and properties.
// object constructor Shape:
function Shape() {
this.name = 'Shape';
}
// object constructor Rectangle:
function Rectangle() {
/* Using JavaScript special function call(),
an object can use a method belonging to another object */
Shape.call(this);
}
// binding prototype, to realize the inheritance
Rectangle.prototype = Object.create(Shape.prototype);
// test inheritance
const rect = new Rectangle();
console.log(rect.name); // expected output: "Shape"
The prototype of an object can be modified. You can add new functions and properties to a prototype using dot notation. When you do, all instances of the prototype will receive the new members.
/* define constructor for Person */
function Person(name) {
// property and method definitions
this.name = name;
// public method: hello
this.hello = function() {
console.log("hello " + this.name);
}
};
/* create an object */
let person = new Person('Smith');
/* extend Person with a new function */
Person.prototype.farewell = function() {
console.log("By "+ this.name );
};
person.hello(); // test internal method
person.farewell();// test external method
Every JavaScript function is actually a Function object. It can be created with alternative notation:
/* alternative notation for function object */
let sum = new Function('a', 'b', 'return a + b');
console.log(sum(2, 6)); // expected output: 8
Note: The example above is only to prove a point. It is not used in practice. The point is: if a function is an object than it can have properties. It means you can create new properties for a function using dot notation. Function properties
Having a property for a function is similar to a static variable. It can take values that are visible from outside the function and can be modified to modify the function behavior.
/* function with static property */
function getNext() {
if (getNext.next == undefined) {
getNext.next = 0;
}
else {
getNext.next++;
}
return getNext.next;
}
/* test static property */
console.log(getNext()); // 0
console.log(getNext()); // 1
getNext.next = 8
console.log(getNext()); // 8
getNext.next = 12
console.log(getNext()); // 13
Observe: You must use: function.property to define function properties. They are attached to function itself not to an object. You can not use this.property to define function properties. That is the difference.
Is your head spinning yet? Sorry, this prototype theory prove to be difficult to grasp and sometimes insufficient.Therefore JavaScript try to evolve and has introduced new concept of "class". This is an attempt to adopt Java style OOP. In fact a "class" is syntax sugar for constructor function. It can be used to create object instances using keyword: "new".
class MyClass {
property_name = value; // class property
constructor(...) { // constructor has always this name
// ...
}
method_name(...) {} // class method
second_method(...) {} // class method
get something(...) {} // getter method
set something(...) {} // setter method
}
In this example you can see 2 classes. One is extending the other. This is how inheritance can be done using the new JavaScript notation.
// base class
class Polygon {
constructor(width, height) {
this.name = "Polygon";
this.width = width;
this.height = height;
}
}
// instantiate object: polygon
let polygon = new Polygon(20,30);
console.log(polygon.name); // "Polygon"
// create a child class
class Square extends Polygon {
constructor(length) {
/* call constructor
of the parent class
this is a mandatory call */
super(length, length);
/* set initial value */
this.name = 'Square';
}
// read-only property
get area() {
return this.height * this.width;
}
};
// test new class: Square
let square = new Square(20);
console.log(square.name); // Square
console.log(square.area); // 400
square.area = 50; // no effect
console.log(square.area); // 400
You can use destructuring assignment with object literals. This is especially interesting when a function return multiple results that need to be assigned to different variables. Deconstructor will read attributes by name and will distribute them into independent variables.JavaScript is weird when it does this. If you are not aware you will not understand the code.
/* declare and initialize object */
let obj = {a: 42, b: true, c:"test"};
/* partial deconstructing object */
let {a, c} = obj;
console.log(a); // 42
console.log(c); // test
/* partial decosntructing one attribute */
let {b} = obj;
console.log(b); // true
/* object with 2 attributes */
let o = {p: 42, q: true};
/* mapping attributes */
let {p: foo, q: bar} = o;
console.log(foo); // 42
console.log(bar); // true
Note: There is more to know about destructuring objects:
Read Mozilla documentation for details:MDN Destructuring
Read next: Collections