Science Library - free educational site

Objects in JavaScript

Object Types

A new object is created using this syntax: var obj = new Object();. If there are no arguments, the parentheses may be omitted, although Best Practice is to include them. This statement is known as an 'instance of the object obj'.

An object instance has these properties and methods: constructor, hasOwnProperty(propertyName), isPrototype(object), propertyIsEnumerable(propertyName), toLocaleString(), toString(), valueOf().

Declaring an Object Class

Objects use data (properties) and functions (methods) in a composite called a class. When a new object is created with this class it is called an instance of the class.

To create a class, write a function (constructor) with the class name. This function takes arguments, and can create the properties and methods for the object created when an instance is called.

function memberEmail(firstname, surname, email)

{

this.firstname = firstname

this.surname = surname

this.email = email

this.listMemberEmail = function()

{

document.write("Member " + this.firstname + " " + this.surname + " has email: " + this.email)

}

}

The object this refers to the instance created each time the function memberEmail is called, allowing the function to be called any number of times.

The call to a second function listMemberEmail within the memberEmail class makes it a method of the class. Functions do not necessarily have to be defined within the class constructor.

function memberEmail(firstname, surname, email)

{

this.firstname = firstname

this.surname = surname

this.email = email

this.listMemberEmail = listMemberEmail

}

function listMemberEmail()

{

document.write("Member " + this.firstname + " " + this.surname + " has email: " + this.email)

}

Creating an Object

To create an instance of a class, first create an empty object: friend = new memberEmail(), then populate it:

friend.firstname = "Freddie"
friend.surname = "McGurty"
friend.email = "info@unimaginativenames.com"

An instance of the new object could also be created by inputting all the arguments in one go:

friend = new memberEmail("Freddie", "McGurty", "info@unimaginativenames.com")

To use the object: e.g. document.write(friend.firstname + ' ' + friend.surname + ' has email: ' + friend.email)


Identifying the Object Type in Javascript

Article by Sean Bone

Often it is necessary to check whether a variable is of a certain type. Consider this function:

  • function media(a, b) {
  • return (a + b) / 2;
  • }

If either of the two arguments, a and b, is not numerical, an error will occur.

isNaN

The function isNaN (is Not a Number) can be used to understand if the object is numerical or not.

Therefore, in our example we can avoid errors:

  • function media(a, b) {
  • if (isNaN(a) || isNaN(b)) {
  • return false;
  • }
  • return (a + b) / 2;
  • }

All well and good for numbers. But what about other objects?

The TYPEOF operator is used to reveal a variable's basic type (boolean, sting, numerical, undefined, function).

Here are some examples:

  • typeof 5 === 'number' // true
  • typeof 3.14 === 'number' // true
  • typeof 'string!' === 'string' // true
  • typeof '' === 'string' // true
  • typeof true === 'boolean' // true
  • typeof function() === 'function' // true
  • typeof Object.toString === 'function' // true

There are, however, some situations in which this operator has an unexpected behaviour:

  • typeof ['a', 'b', 7] === 'object' // true: in fact, array is not a basic type - arrays are instances of the Array object
  • typeof null === 'object' // true: this is a peculiarity of JavaScript, existing for historical reasons
  • typeof new String('string!') === 'object' // true: this causes confusion - do not use this form!
  • typeof new Number(3.14) === 'object' // as above
  • typeof new Boolean(true) === 'object' // as above

The INSTANCEOF operator

In general, the best method is the instanceof operator, in the form a instanceof b, returns true if a is an instance of b, otherwise false.

  • A = function() {}
  • B = function() {}
  • obj = new A();
  • obj instanceof A // true
  • obj instanceof B // true, since B is not a prototype chain of obj
  • obj instanceof Object // true, since:
  • A.prototype instanceof Object // true, therefore Object is a prototype chain of obj

Returning to the last examples of the typeof operator:

  • ['a', 'b', 7] instanceof Array // true
  • new String('string!') instanceof String // true
  • new Number(3.14) instanceof Number // true
  • new Boolean(true) instanceof Boolean // true

Unfortunately, however, this method also has its little problems. It does not function with an Array from another frame (i.e. from an Iframe).

So, how is possible to create a function which is reliable, checking whether an object is an Array or not?

One solution is surprisingly simple: the toString method, which gives the type of object in the form of a string:

  • function isArray(o) {
  • return Object.prototype.toString.call(o) === '[object Array]';
  • }


Sean Bone

ZumGuy Network webmaster

Visit my Internet forum: ZumGuy Internet Forum

Per una versione di quest'articolo in Italiano vedi: Javascript: identificare il tipo di un'oggetto

Translation by Transalpine Technical Translations.

The DOM Model

JavaScript utilises the DOM to identify and locate precise elements of a page. In this example, the HTML code "Date()" will be substituted in the element with the ID 'date_button'. Since the HTML is a date function inside a button tag, it will remove any existing HTML and display the current date and time when the button is clicked.

<button type="button"

onclick="document.getElementById('date_button').innerHTML = Date()">

Date Button.

<p id="date_button">

This text will be replaced by the date and time

Content © Andrew Bone. All rights reserved. Created : April 5, 2014 Last updated :March 10, 2016

Latest Item on Science Library:

The most recent article is:

Air Resistance and Terminal Velocity

View this item in the topic:

Mechanics

and many more articles in the subject:

Subject of the Week

Environment

Environmental Science is the most important of all sciences. As the world enters a phase of climate change, unprecedented biodiversity loss, pollution and human population growth, the management of our environment is vital for our futures. Learn about Environmental Science on ScienceLibrary.info.

Environmental Science

Great Scientists

Arthur Eddington

1882 - 1944

Arthur Stanley Eddington, 1882 - 1944, was an English astronomer, best known for his confirmation of Einstein's General Relativity Theory, by measuring the gravitational lensing of the Sun during a solar eclipse on 29 May, 1919.

Arthur Eddington, 1882 - 1944, English physicist
Lugano English

Quote of the day...

Sean couldn't believe what he was hearing. If his maths teacher could hear this... "But I thought Euclid was the Father of Geometry?".
"What he fathered in his private life is none of my concern," went on Luca.