JavaScript Objects

JavaScript is an awesome language but at the same time JavaScript is a frustrating language.

Every developer will have this love hate relationship with JavaScript. Developers just don’t know how to define JavaScript : Is it Object Oriented? is it a Functional language? Is it an interpreted language , is it a dynamic language? The truth is, JavaScript comprises of elements of all, and unfortunately not always the in a good way.

At the core of JavaScript is the Object .

Everything is an object and the object is everything!

Nearly everything in JavaScript is an object, including functions. Because of that feature, functions can be used anywhere you might use a variable, including the parameters in function calls. In JavaScript an object is just a container for a collection of named values, otherwise known as properties.

mutable & immutable

An important thing to note here is that in JavaScript an object is mutable and the simple data types are immutable.

Reference Data Type and Primitive Data Types

In JavaScript both Reference Data Types and Primitive data types are compared by value. There are some interesting edge cases and potential side effects of this functionality you need to be aware of, as the name implies reference data types values are stored as a reference, where as primitive data types are stored as values.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

// The primitive data type String is stored as a value

​​varperson="Gary";​

varanotherPerson=person;// anotherPerson = the value of person​

person="John";// value of person changed​​

console.log(anotherPerson);// Should Print Gary

console.log(person);// Should Print John

//In the next example we'll create an object and change it's value

varperson={name:"Gary"};

varanotherPerson=person;

person.name="John";

console.log(anotherPerson.name);// Should Print John

console.log(person.name);// Should Print John

NB : objects are really just containers for properties, each of which has a name and a value. This notion of a container of properties with named values (i.e. an object) is used by JavaScript as the building blocks for expressing values in JavaScript.

Configurable : Specifies whether the property can be deleted or changed.

Enumerable : Specifies whether the property can be returned in a for/in loop.

Writable : Specifies whether the property can be changed.

As previously stated before, everything in JavaScript is an object. Even JavaScript types like the String, Number, Date, Boolean are objects. These objects also have constructor functions baked into the language to make the creation of these objects a trivial task.

1

2

3

4

5

6

7

8

9

10

11

12

13

varmyStringObject=newString('Gary Woodfine');

varmyObjectObject=newObject();

varmyDateObject=newDate();

varmyBooleanObject=newBoolean();

myObjectObject['Name']='Gary Woodfine';

console.log(myObjectObject);

console.log(myStringObject);

console.log(myDateObject);

console.log(myBooleanObject);

As it turns out all of the above are objects as they can have properties, inherit properties, and are produced from a constructor function. It is also possible to create your own powerful object constructor functions .

Object Constructor

You may need to create non-native custom object constructor functions to help other developers to create objects from it. In my case below I want to create a Freelancer object so that I can create a number of freelancer objects from it with all the same traits.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

/* Freelancer is a constructor function It was written with the intent of being used with the new keyword. */

varFreelancer=function(name,location,rate,available){

// "this" below is the new object that is being created

this.name=name;

this.location=location;

this.rate=rate;

this.available=available;

this.getAvailability=function(){returnthis.available;};

};

vargary=newFreelancer('Gary Woodfine','United Kingdom',1000,true);

console.log(gary);

console.log(gary.getAvailability());

Prototype

In addition to having maintaining their own set of properties JavaScript objects also inherit the properties of another object known as its prototype . Every JavaScript object has a second object associated with it, known as its prototype, and the first object inherits properties from the prototype.

The methods of an object are typically inherited properties and this is called prototypal inheritance.

JavaScript objects are dynamic, meaning properties can be added and deleted.

Creating objects

The most common things to do with objects are to create them and to set, query, delete, test and enumerate their properties.

A property name may be any string, including an empty string, but no object may have two properties with the same name. The value may be any JavaScript value, or it may be a getter or a setter function or both.

The easiest way to create an object is to include an object literal in your JavaScript code. An object literal is a comma-separated list of colon-separated name:value pairs enclosed in curly braces.

Creating Objects with new keyword

The new keyword creates and initializes a new object and must be followed by a function invocation. A function used in this way is called a constructor and serves to initialize a newly created object. Core JavaScript includes built-in constructors for native types.

1

2

3

4

5

// Core constructor objects

varobject=newObject();// Create an empty object i.e. {}

vardate=newDate();// Create a Date Object

vararray=newArray();// Create an empty array i.e. []

varregex=newRegExp("js");// Create a Regular Expression object

Objects created using the new keyword and constructor invocation use the value of the prototype property of the constructor functions as their prototype.

Object.create()

In the specification of ECMAScript 5, an object.create() method is defined, which is a static function invoked on individual objects.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

//Create an object with some properties

varpersonObject={Name:"",LastName:"",Hair:"",Eyes:"",Job:""};

//Create a new object inherit properties from the base object

vargary=Object.create(personObject);

gary.Name="Gary";

gary.LastName="Woodfine";

gary.Job="Freelance Software Developer";

gary.Eyes="Blue";

gary.Hair="Brown";

for(varprop ingary){

if(gary.hasOwnProperty(prop)){

console.log(prop+" = "+gary[prop]);

}

}

The role of a constructor function is to create multiple objects that share certain qualities and behaviors. Basically, a constructor function is a cookie cutter for producing objects that have default properties and property methods.

In JavaScript, most values involve objects being created, or instantiated, from a constructor function. An object returned from a constructor is called an instance. Make sure you are comfortable with these semantics, as well as the pattern of leveraging constructors to produce objects.

Native JavaScript object constructors

The JavaScript language contains nine native or built-in object constructors. These objects are used by JavaScript to used to express object values in JavaScript code, as well as orchestrate several features of the language. The native object constructors are multifaceted in that they produce objects, but are also leveraged in facilitating many of the language’s programming conventions. For example, functions are objects created from the Function() constructor, but are also used to create other objects when called as constructor functions using the new keyword.

Helps businesses by improving their technical proficiencies and eliminating waste from the software development pipelines.

A unique background as business owner, marketing, software development and business development ensures that he can offer the optimum business consultancy services across a wide spectrum of business challenges.