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.

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

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:

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:

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,

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.

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:

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");

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

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.

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.

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.

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:

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

And you can delete properties.

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)

Advertisements