My FeedDiscussionsHeadless CMS
New
Sign in
Log inSign up
Learn more about Hashnode Headless CMSHashnode Headless CMS
Collaborate seamlessly with Hashnode Headless CMS for Enterprise.
Upgrade ✨Learn more
JavaScript Objects

JavaScript Objects

Theresa's photo
Theresa
·Sep 25, 2016

The first time I was introduced to working with objects while programming was when I was introduced to OOP. But to be able to work in an Object Oriented fashion starts by understanding objects. First things first: working with objects does not imply object orientation. An object in JavaScript is created using an object definition; must be initialized by creating an instance of the object; may be retrieved by looping through the items or properties in the object definition.

Insert statements assign values to each object property; and may be extended using the intrinsic prototype property to add more object properties or methods:

// creating an object
function Book (page, cover, color) {
       this.page = page;
       this.cover = cover;
       this.color = color;
}

// initialize 
var myBook = new Book ( 'one', 'leather', 'black' );

// add property and assign it a value
Book.prototype.text = 'This text may be assigned to my first page' ;

// write your object name and value to screen
for ( property in myBook ) {
      someContainer.innerHTML += property + ': ' myBook [ property ] +           '<br>';

You can now reuse your book object in your application by creating new books, assigning new values for its properties.

Instances inherit the properties specified in the prototype. When you extend an object prototype, all further instances of that object will also inherit the extended properties specified (as seen when we added text later).

Objects are great because by introducing them to a system, you can save a lot of time and code. Like if you own a library and a bookshop, both have book objects as their base, and they have the same properties... well mostly... but perhaps books in a bookshop has a price and books in a library will want to have a property to store the ID of the last person who borrowed the book.

Try introducing objects to your next project. It would be great to Compare notes on what worked for your project and what did not and why :)