Objects in programming language are a certain approximation of objects in the real world, for example wallet, engine, telephone. Each object in real world has its own state and behavior. In programming language state of the object is stored in fields and its behavior is expressed through methods.
Nature of JavaScript objects
JavaScript object is unordered collection of properties, where each property has a name and value. A property’s value can be a primitive value, object or function. In the last case the property is called a method.
You can distinguish three categories of objects:
- Native objects are instances of object types and objects defined by the ECMAScript specification (eg. Object, Array, Date, Math),
- Host objects are objects defined by host environment like a web browser (eg. document, Node)
- Objects defined by users.
Creating objects
An object can be created in several different ways. Usually you will create an object with object literal, or with a constructor function.
Creating objects with object literal
Object can be create with an object literal. An object literal is enclosed in curly braces ({}) a comma-separated list of property name : value pairs.
// an object with 3 properties var obj = { prop1 : 'alpha', prop2 : 100, prop3 : true }; // an object with no properties var obj = {};
An object literal is an expression and whenever it appears, it creates new, distinguish object. an object created with object literal is like created with new Object() and is a instance of Object.
Creating objects using constructor function
To create an object with constructor function use the new keyword followed by a constructor invocation. The syntax is as follow:
var obj = new Constructor();
The new operator creates a new object. A function that follows it is a constructor and its task is to initialize the object.
Build-in constructors
JavaScript provides constructors for native object types like Object, Array, Date. You can use them to create an objects.
var myObject = new Object(); // creates an empty object, equivalent of {} myObject.prop1 = 'alpha'; myObject.prop2 = 100; myObject.prop3 = true;
The Object is a general object type and all other objects inherit properties from it.
Examples of use more specific object types:
var myArray = new Array(); // creates an empty array, equivalent of [] var myDate = new Date(); //
User defined constructors
You can define your own object type and create instance of it. To do this define a function, specify its name, properties and methods. Such a function is called a constructor.
function Person(name, surname) { this.name = name; this.surname = surname; this.introduceYourself = function() { return "I'm " + this.name + " " + this.surname; }; } var person = new Person('John', 'Doe');
Creating objects with the Object.create
Each object in JavaScript inherits properties from some other object. This object is called prototype. Rarely, the prototype of the object can be set to null. Objects created by object literal have Object.prototype prototype. All instances of built-in object types also inherit from Object.prototype prototype.
Object.create() function allows you to create a new object and specify in the first argument the prototype of that object.
var obj = Object.create(Object.prototype); // equivalent of {} or new Object()
Properties
State of the object is stored in its fields, behaviour in its methods. These fields and methods are called object properties. A property of an object is similar to a variable although they are not the same. Property is enclosed in the object, has a name, a value and also some other features. The properties specify characteristic of the object.
Access to properties
To access an object property use an object identifier followed by dot (.) and property name.
var value = objectName.propertyName;
To add property to the object or update its value use the same notation as you would to access it and assign to it a value.
var address = {town: "Dublin"}; address.town = "Galway"; var address.street = "Quay";
The second way to get access to the object’s property is to use square brackets ([]). Specify an object identifier followed property name enclosed in square brackets.
var value = objectName["propertyName"]; var address = {town: "Dublin"}; address.["town"] = "Galway"; var address["street"] = "Quay";
Objects in JavaScript are similar to associative arrays. Property name is like string key, using it with the square brackets notation you can get access to the property value. Another similarity is that objects do not have a fixed number of properties like in some other programming languages. A new properties can be added to the object at any time.
Property name can be any valid string, even the empty string. With dot (.) notation you can access only valid JavaScript identifiers. If you want to use property name that is not a valid identifier, you should use square bracket notation.
var obj = {}; obj['Jack Smith'] = 28; obj['012hash'] = 1234; obj[''] = 0.01;
If a property is referred by the . operator its name has to be identifier literally written in the code. The [] array operator allows you to access properties by using a string value stored in a variable. Another possibility that the [] array operator gives you is the use of property names as strings dynamically created while the program is running.
var product = new Object(); var propertyName = 'name'; product[propertyName] = 'camera'; var propertyName2 = 'price'; product[propertyName2] = 150; var items = {item1 : 'flour', item2 : 'sugar', item3 : 'milk'}; for (var i = 1; i <= 3; i++) { console.log(items['item' + i]); }
Attempt to access a property that do not exists in an object is not an error. If a property is not found in an object, property access expression returns undefined.
var car = {bodyType : 'hatchback'}; var engine = car.engine; // undefined
An error is however when you query a property of an object that do not exist. If you query properties of expressions that evaluates to the undefined or the null value it causes an error.
var engineSize = car.engine.size; // TypeError: car.engine is undefined
To omit an error you should check if the value is an object.
var engineSize = 'unknown'; if (car && car.engine) { engineSize = car.engine.size; }
Checking properties
Sometimes it is useful to check if an object has given property. JavaScript provides several possibilities to do this: by querying the property, the in operator, the hasOwnProperty() method.
The simplest way is to query the property and check whether it is not undefined.
var building = {room : {name : 'living room'}}; if (building.room !== undefined) // true, building has a property room if (building.alarm !== undefined) // false, building does not have a property alarm
The in operator is more convenient than querying the property. Additionally it allows you to check whether property exists even if it is set to undefined. It returns true if the object has own property with the given name or inherits it. The in operator expects property name on its left and a tested object on the right.
var building = {room : 'kitchen', ventilation : undefined}; if ('room' in building) // true, building has a property room if ('ventilation' in building) // true, building has a property ventilation if ('lighting' in building) // false, building does not have a property lighting
The hasOwnProperty() method returns true if the object has own property with given name and does not include inherited properties.
var building = {room : 'cellar'}; if (building.hasOwnProperty('room')) // true if (building.hasOwnProperty('heating')) // false if (building.hasOwnProperty('toString')) // false, toString property is inherited
Deleting properties
It is possible to remove a property from an object. To do this, use the delete operator and as an operand, specify the property of the object. In this way you can delete only own properties, not inherited.
var data = {name : 'Max Doe', age : 33, salary : 3000}; delete data.age; delete data['salary'];
Getters and setters
JavaScript has the functionality of getters and setters. You can define properties known as accessor properties which instead of value contain a combination of getter function and setter function. When an accessor property is read, the getter function is called. It should return a proper value and before it can execute some additional statements. When an accessor property is set, the setter function is called. It should set a new value and can execute some additional statements.
To create getter and setter in the object literal the syntax is as follow:
var obj = { ordinaryProperty : 'value', get accessorProperty() { // additional statements return this.ordinaryProperty; }, set accessorProperty(value) { this.ordinaryProperty = value; // additional statements } };
Accessor properties are defined as functions with the same name as the property. Instead of the function keyword is used get or set followed by the normal function definition.
var publication = { text : 'some interesting text here', readingCounter : 0, changesCounter : 0, get content() { this.readingCounter++; return this.text; }, set content(text) { this.text = text; this.changesCounter++; } }; console.log(publication.content); console.log(publication.readingCounter); // 1 publication.content = 'nothing interesting'; console.log(publication.text); // nothing interesting console.log(publication.changesCounter); // 1
Methods
A method is a functions that is assigned as the property of an objects.
Instances of build-in object types have some build-in methods. For example every object has the toString() method.
var obj = new Object(); console.log(obj.toString()); // [object Object]
To create your own method define an anonymous function and assign it to an object property.
var space = { volume : 100, take : function(amount) { var allocatedSpace = 0; if (this.volume > amount) { this.volume = this.volume - amount; allocatedSpace = amount; } else { allocatedSpace = this.volume; this.volume = 0; } return allocatedSpace; } }; space.take(10); // call the space.take() method
You can add a new method to an existing object.
space.give = function (amount) { var returnedSpace = 0; if (this.volume + amount <= 100) { returnedSpace = amount; 100 - this.volume; this.volume = this.volume + amount; } else { returnedSpace = 100 - this.volume; this.volume = 100; } return returnedSpace; }; space.give(5);
The this keyword
The this keyword is a reference to the current object in the object’s method. It is not property or variable. It cannot be inherited by a nested function. You can use it to access properties of the current object, to call its methods or to return the current object.
var myTest = { data : '###', printData : function() { console.log(this.data); }, test : function() { this.data = 'xyz'; this.printData(); var that = this; internalTest(); function internalTest() { that.data = 'abc'; that.printData(); } } }; myTest.test(); // Output: // xyz // abc
Object reference
Objects in JavaScript are always passed by reference, never by copied value. This means that if one variable to which the object is assigned will be assigned to the other, both will be refer to exactly the same object. The value in the case of objects is in fact pointer to an physical address where the object is stored. Thus both variables point to the same object. Consequently, changes made to one of them are reflected in the other.
var objectA = {value : 100}; var objectB = objectA; objectB.value = 250; console.log(objectA.value) // 250
Reply