Object JavaScript – Getting Started with Objects the Way JavaScript Thinks About Objects

10063_580983808600819_401360548_nThis post begins a series on how you can write better JavaScript.

The purpose of this series is take your knowledge to the next level, for you to add skills that will help you build commercial-quality code.

JavaScript objects were introduced in the ECMAScript 5 specification.

In this post, you will learn

  • Create objects using a constructor and literals.
  • How to access property values.
  • How methods operate on an object.
  • What an instance is.
  • Identify important objects used in JavaScript

You should already know how the basics of JavaScript. For example, how to write statements, blocks, comments, declare and assign variables, write if then else, put up alerts, call a function, create a function, for loops, while loops, do loops, connect up a onclick and onmouseover events to HTML, implement try catch, and setTimeOuts.

Introduction to Objects

JavaScript is objects. Everything is an object: strings, numbers, arrays, functions.You can think of a JavaScript object as a special kind of data – one that includes properties and methods.

JavaScript objects are defined in the ECMAScript standard specification, which is supported in modern browsers.

ECMAScript does not use classes such as those in C++, Smalltalk, or Java. Instead you can create objects several ways including via a literal notation or via constructors which create objects.

Any value in JavaScript that is not a string, a number, true, false, null, or undefined is an object.

Properties

An object is a container for a bunch of values and methods.

A property is a name and value.

Let’s look at a sample object.

image

You initialize all or part of any object by assigning initial values to their properties.


var laundryTask = new Object();
laundryTask.description= "Get shirts";
laundryTask.hoursToComplete = 1;
laundryTask.urgency = "low";
laundryTask.done = false;
console.log(JSON.stringify(laundryTask));

An alternative syntax can also initialize an object using object literals. For example:


var laundryTask = {
description: "Get shirts",
hoursToComplete:1,urgency="low",
done=false
};

More on literals in a following section.

You can also create an object using this syntax:

var laundryTask = {}; // declares a new object

laundryTask.description= "Get shirts";
laundryTask.hoursToComplete = 1;
laundryTask.urgency = "low";
laundryTask.done = false;

console.log(JSON.stringify(laundryTask));

Property Methods

You can have a getter and setter functions.

I will want to be able to get the value of a task programmatically. Methods are properties that contain a function() object, whose intent is to operate on the object.

In the example, we can add a getUrgency() method that will retrieve the urgency of the task object.

image

The getUrgency() method would look like this:

var laundryTask= new Object():

laundryTask.description= "Get shirts";
laundryTask.hoursToComplete = 1;
laundryTask.urgency = "low";
laundryTask.done = false;
laundryTask.getUrgency = function() {
    return task.urgency;
} 

console.log(laundryTask.getUrgency());

Creating Objects

There are several ways to create object in JavaScript:

  • Literal
  • Constructor using new keyword
  • Prototypes

Constructors

As you see, you can construct your object from the Object() constructor function. In fact, most of the values expressed in JavaScript are really objects. For example, string is an object that has properties and has a constructor function.

You can declare a string like this:

var aString = new String("my new string");

For our tasks, we might want to create code with a bigger idea than just laundryTask. We might be able to use the same code for a more generalized Task object by using a constructor.

A constructor prepares the new object for use, often accepting parameters that the constructor uses to set member variables required for the object to reach a valid state. It is called a constructor because it constructs the values of data members of the class.

You can use a constructor like this:


var Task = function(description, hours, urgency, done){
this.description = description;
this.hoursToComplete = hours;
this.urgency = urgency;
this.done = false;
}
var laundryTask = new Task("get shirts", 1, "low", false);
console.log(JSON.stringify(laundryTask));

We can create Task objects now, just as we do with String objects.

The Task() constructor constructed laundryTask but can be used as a powerful, centrally defined object factory to be used for creating more Task() objects. As you craft your own constructors for producing custom objects you build up prototypes and the ability to inherit behaviors in your Task() instances.

Instances

Once you have a object constructor, you can create new instances of the object, like this:


var laundryTask = new Task("get shirts", 1, "low", false);
var shoppingTask = new Task("groceries", 3, "high", false);
console.log(JSON.stringify(laundryTask));
console.log(JSON.stringify(shoppingTask));

Use a constructor function 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.

new Keyword

A constructor uses the new keyword.  The new keyword must be followed by a function. A function used in this way is called a constructor and serves to initialize a newly created object.

When you use the new keyword, JavaScript treats the function as special by setting the value of this for the function to the new object that is being constructed.

The new object that is returned from the function is an instance of the constructor function that constructs it.

Each constructor is a function that has a property named ― prototype that is used to implement prototype-based inheritance and shared properties. More on prototypes in the next post in this series.

Objects are created by using constructors using new expressions; for example,


var myDate = new Date(2009,11);

view raw

ojs-new.js

hosted with ❤ by GitHub

creates a new Date object. Invoking a constructor without using new has consequences that depend on the constructor. For example, Date() produces a string representation of the current date and time rather than an object.

Literals

An object literal is an expression that creates and initializes a new and distinct object each time it is evaluated.

Literals let you build objects “on the fly”. Object literals are used to encapsulate data, enclosing your data into a single object to minimize the use of global variables.

Literal can contain arrays or arbitrary JavaScript expressions or values.

When you use literals, you do not need to invoke constructors directly or maintain the correct order of arguments, instead you specify them.


var laundryTask = {
description: "get shirts",
hoursToComplete: 1,
urgency: "low",
done: false
};

view raw

ojs-literals.js

hosted with ❤ by GitHub

Object literals are also useful for unobtrusive event handling, as a way of holding data that would otherwise have been passed to functions called from HTML event handler attributes.

Here are some examples of literals in action:


var empty = {}; // An object with no properties
var point = { x:0, y:0 }; // Two properties
var point2 = { x:point.x, y:point.y+1 }; // More complex values
var book = {
/* property names can include spaces and hyphen
and quoted reserved words. */
"main title": "HTML5",
'sub-title': "For All Devices",
"for": "age 13 and up",
// And can include another object
author: {
firstname: "Bruce",
lastname: "Kyle"
}
};

Built in Constructors

JavaScript comes with a set of native objects. Here are a list of some with some comments:

  • Number(). All numbers in JavaScript are stored as 64-bit (8-bytes) base 10, floating point numbers.
  • String(). You can access each character in a string with its position (index). String indexes are zero-based.
  • Boolean().
  • Object()
  • Array().You Can Have Different Objects in One Array
  • Function()
  • Date(). Once a Date object is created, a number of methods allow you to operate on it. Most methods allow you to get and set the year, month, day, hour, minute, second, and milliseconds of the object, using either local time or UTC (universal, or GMT) time.
  • RegExp(). A regular expression is an object that describes a pattern of characters. When you search in a text, you can use a pattern to describe what you are searching for.
  • Error()

And they come with their own set of functions that make JavaScript rich. For example, you can use built in functions on the Array() object. If you have an array:


var myFlowers = new Array("Rose","Carnation","Tulip");

view raw

ojs-array.js

hosted with ❤ by GitHub

 

var myFlowers = new Array("Rose","Carnation","Tulip");

You can then use methods and properties on the array object. For example:


var x = myFlowers.length; // the number of elements in myFlowers
var y = myFlowers.indexOf("Carnation"); // the index position of "Carnation"

Copying, Equals

Objects are mutable and are manipulated by reference rather than by value. If the variable x       refers to an object, and the code var y = x; is executed, the variable y holds a reference to the same object, not a copy of that object. Any modifications made to the object through the variable y are also visible through the variable x.


function changeStuff(num, obj1, obj2)
{
num = num * 10;
obj1.item = "changed";
obj2 = {item: "changed"};
}
var num = 10;
var obj1 = {item: "unchanged"};
var obj2 = {item: "unchanged"};
changeStuff(num, obj1, obj2);
console.log(num);
console.log(obj1.item);
console.log(obj2.item);

Object Attributes

Every object has three associated object attributes:

  • An object’s prototype is a reference to another object from which properties are inherited.An object’s class is a string that categorizes the type of an object.
  • An object’s extensible flag specifies (in ECMAScript 5) whether new properties may be added to the object.

We’ll describe prototypes in the next post.

More About Properties

Each property also has additional descriptors that can be applied:

  • writable attribute specifies whether the value of the property can be set.
  • enumerable attribute specifies whether the property name is returned by a for/in loop.
  • configurable attribute specifies whether the property can be deleted and whether its attributes can be altered.

To change the default property attributes, use the Object.defineProperty() method. It accepts three arguments: the object, the name of the property, and a descriptor.


var bruce = {};
Object.defineProperty(bruce, "name", {
writable: false,
value: "Bruce"
});

In this example, we defined a bruce object that did not have any properties. Then added the name property that is read-only. In strict mode, an error is thrown if you try to change bruce.name.

You can get information about the property descriptors too.


var descriptor = Object.getOwnPropertyDescriptor(bruce, “name”);
console.write(descriptor.value); // bruce
console.write(descriptor.enumerable); //false
console.write(descriptor.writable); // false

Objects As Associative Arrays

The first syntax, using the dot and an identifier, is like the syntax used to access a static field of a struct or object in C or Java. The second syntax, using square brackets and a string, looks like array access, but to an array indexed by strings rather than by numbers. This kind of array is known as an associative array (or hash or map or dictionary).

These are the same:

  object.property
  object["property"]

You can do interesting things because the property can be assigned at runtime. In the following example, you can reference a stock using the stockname assigned at runtime with the number of shares:


function addstock(portfolio, stockname, shares) {
portfolio[stockname] = shares;
}

You can loop through the properties in an object. For example:


var myHelloObj = {
prop1:"hello",
prop2:"hello2",
prop3:new Array("helloa",1,2)
}
for(x in myHelloObj console.log( x + "-" + myHelloObj [ x ] );

And you can delete properties.


delete book.author; // Deleted the book author property.
delete book["main title"]; // Now it doesn't have "main title", either

Best Practice

When creating custom constructor functions intended to be used with the new operator, it’s best practice to make the first character of the constructor name uppercase: Task() rather than        task().

References

ECMA Script specification

JavaScript and Object Oriented Programming (OOP) from JavaScript Kit

Introduction to Object-Oriented JavaScript on Mozilla Developer Network

Is JavaScript a pass-by-reference or pass-by-value language?

Books

JavaScript Enlightenment

JavaScript: The Definitive Guide: Activate Your Web Pages (Definitive Guides)