w3resource

JavaScript Object

Introduction

JavaScript is not a full-blown object-oriented programming language, such as Java, but it is designed on a simple object-based model. An object is a construct with properties that contain JavaScript variables or other objects. An object also has functions associated with it that are known as the object's method. You can define your own object in addition to JavaScript core (such as array or math) objects.
Since JavaScript is a loosely-typed, dynamic and expressive language, you may accomplish the same task in various ways. The purpose of this tutorial is to provide you with a guide to unleshing the potential of the language (in the context of creating and using objects) and in turn helping to you understand what happens behind the scene. It can not be claimed that the ways described here are the only ways to do stuff. Rather, it would be great, if this helps you anyway to choose your own methods.

Contents:

JavaScript Object

"Everything" in JavaScript acts like an object such as a String, a Number, an Array, a Function..., with two exceptions, null and undefined.

JavaScript: Creating Objects

In JavaScript, there are many ways to create objects. You can create an object using an object initializer or write a constructor function to define the object type and create an instance of the object with the new operator. JavaScript's "Object initializer" is consistent with the terminology used by C++.

Syntax

Using an object literal - {} notation you can create a plain object:

var objectName = {}

or

You can create new object by defining properties and values:

var objectName = { property1 : value1,
                   property2 : value2,
                   //...,
                   propertyN : valueN }; 

where

objectName : Name of the new object.

property_1, property_2, .....property_n : An identifier (either a name, a number, or a string literal).

value1, value2,..,valueN : An expression whose values are identified by property_1, property_2, .....property_n.

In JavaScript, you can create a new object without creating a class. The object does not belong to any class; it is the only one of its kind. You can use the typeof operator to get the data type of a newly created object. See the following example :

* To run the code mouse over on Output panel and click on 'Run with JS' button.*

JS Bin on jsbin.com">Check the type of an object

Example: Object initializers

The following codes create an object "student" with three properties name, sclass and rollno.

 var student = {
                name : "David Rayy", 
                sclass : "VI", 
                rollno : 12 
               } 

Using a Constructor function

Here is another way to create an object.

First define the object type by writing a constructor function, then create an instance of the object with new.

To write a constructor function, we should maintain the following rules.

  • The constructor function name will be the object type name.
  • In the constructor function, this operator is used to refer the current object.
  • The properties/methods have their values defined after an equal sign '='.
  • There will be no "return" statement in the constructor function.

Example of a Constructor function

Here is an example of a constructor function:

function student(name, sclass, rollno)
   {
     this.name = name;
     this.sclass = sclass;
     this.rollno = rollno;
   }

The type of the above object is a student with three properties name, sclass, and rollno. The value of the object's depends on the parameters passed to the function. Lets create an object called studentv as follows :

studentv = new student("John", "V", 10); 

The above statement creates an object called studentv and assigns it the specified values for its properties. Therefore the value of studentv.name is the string "John", studentv.sclass is the string "V" and student.rollno is the integer 10. You can create any number of student objects using new operator. For example -

studentv  = new student("John", "V", 10);
studentvi = new student("Scott", "VI", 2);

Objects and Properties

Properties  are characteristics of the object. A JavaScript object has properties associated with it. For example the document object has a property called fgColor that describes (document.fgColor = "color_name") the background color of that object. The properties of an JavaScript object are basically same as JavaScript variables except the attachment of an object name with dot-notation.

In javaScript, both object name and property name are case sensitive. You can define a property by assigning it a value. Let assume that there is an object called student with three properties name, sclass, rollno. They have defined as follows :

student.name = "David Rayy";
student.sclass = "V";
student.rollno = 1 ;

Properties of JavaScript objects can also be set using a  square bracket notation. Objects and arrays in JavaScript are closely related, actually they are different interfaces to the same data structure. You can set the properties of the previous student object as follows :

student.["name"] =  "David Rayy";
student.["sclass"] =  "V";
student.["rollno"] = 1;

The type of the said array is known as an associative array as each index element is also associated with a string value.

Accessing Properties

There are two ways to access the properties of an object, via the

  • dot notation
  • square bracket notation.

Both the notations work identically. The square bracket notation are used to determine the property name when the properties are set dynamically (i.e. property name is not determined until runtime).

var color = {name: 'red'};
color.name; // red
color['name']; // red

var get = 'name';
color[get]; // red

Deleting Properties

The delete operator deletes an object's property. If you set the property to null or undefined it only removes the value associated with the property, but not the key. See the following example:

var obj = {
    property1 : 'value1',
    property2 : 'value2',
    property3 : 'value3'
};
obj.property1 = undefined;
obj.property2 = null;
delete obj.property3;

JavaScript: Defining Methods

In JavaScript objects' methods run "inside" that object. A method is a function associated with an object. The keys of objects are called properties which are containers for primitive values and other objects. In case, when properties contain functions as their values, they are called methods. Methods are defined the way normal functions are defined, except that they have to be assigned as the property of an object. See the following code :

Syntax

 
  var myObj = {
       ...
       methodName: Myfunction(parameters) 
{ statements; }
}
;

Where

  • "myObj" is the name of an object.
  • "methodName" is the name of the method.
  • "Myfunction" is the name of the function.

You can call the above method in the following way :

myObj.methodName(parameters);

You can define methods for an object type by including a method definition in the object constructor function. For example, you could define a function that would format and display the properties (i.e. name, class, rollno) of the previously-defined student object; See the following example :

function studentDetails() 
{
alert(
"The name of the student is " + this.name + " Class : " + this.class        + " Roll No.: " + this.rollno)
}

where alert() - display the details of a student.

To make this function a method of student object, following code can be used :

this.studentDetails = studentDetails; to the object definition.

Therefore the full definition of student would now look like :

function student(name, class, rollno)
{ 
this.name = name 
this.class = class
this.class = rollno
this.studentDetails = studentDetails
} 

Example: Student Object

HTML Code

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>working-with-objects-1</title>
</head>
<body>

</body>
</html>

JS Code

var fruitslist = new Array("Orange","Apple","Banana","Chery" );
var newParagraph = document.createElement("p"); 
var newText = document.createTextNode("List of Fruits : " + fruitslist); 
newParagraph.appendChild(newText); 
document.body.appendChild(newParagraph); 

var newfruitslist =fruitslist.slice(1,3);
var newParagraph = document.createElement("p"); 
var newText = document.createTextNode("Extract Fruits List : " + newfruitslist); 
newParagraph.appendChild(newText); 
document.body.appendChild(newParagraph); 

More example of JavaScript method

HTML Code

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
 <meta name="viewport" content="width=device-width">
  <title>working-with-objects-2</title>
</head>
<body>

</body>
</html>

JS Code

var myObj = { // object "myobj" with three properties: x, y, z
  x: 100, // primitive value
  y: {a: 12}, // object "y" with property a
  z: function() // function abc -> (method)
      {  
       console.log('Method myObj.z');
      }
};
console.log(myObj.x); // 100
console.log(myObj.y); // [object Object]
console.log(myObj.y.a); // 12
myObj.z(); // 'Method myObj.z'

The Prototype

In our previous section, we have discussed objects as simple pairs of keys and values. But there is an additional attribute in JavaScript object, a pointer to another object which is called the object’s prototype.

  • JavaScript does not support a classical inheritance model, instead, it uses a prototypal one.
  • Every object in JavaScript contains a reference to its prototype
  • The default is object.prototype
  • Strings use String.prototype, etc.
  • A prototype can have a prototype, and so on.
  • An object inherits all property/methods from its prototype(s)

In the following example we have created a constructor function and add a method ('display') to the function's prototype property, and then create a new object ('stu1').

HTML Code

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>working-with-objects-3</title>
</head>
<body>

</body>
</html>

JS Code

// Constructor function student
function student() {
    this.name = "Robert";
}
// add a method ti function's prototype
student.prototype.display = function() {
   console.log("My name is  " + this.name);
};
// create a new object stu1 
var stu1 = new student();
// stu1 can access the display() method
stu1.display();

Now the newly created object 'stu1' can access all the properties which were defined on the constructor function's prototype.

Deleting Objects

Using delete operator we can remove an object. See the following codes how to remove an object.

myobj= new Array(element1, element2)

delete myobj

Practice the example online

See the Pen javascript-common-editor by w3resource (@w3resource) on CodePen.


Previous: JavaScript: decodeURIComponent functions
Next: JavaScript: Core Objects

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://www.w3resource.com/javascript/object-property-method/working-with-objects.php