JavaScript Objects – JavaScript Object Methods & Prototypes

In this JavaScript Tutorial, we will learn objects in JavaScript, its properties, object methods, the creation of objects in JavaScript, different types of objects, JavaScript objects prototype and getters, and setters.

Firstly, we will introduce you with JavaScript Objects.

JavaScript Objects

1. Introduction to JavaScript Objects

Objects in JavaScript are its most important data type and forms the building blocks for modern JavaScript. These objects are quite different from JavaScript’s primitive data types ( Numbers, String, Boolean, Null, Undefined, Symbol) in the sense that while these primitive data types all store a single value each (depending on their types).

  • Objects are more complex and each object may contain any combination of these primitive data types as well as reference types.
  • An object is also a reference data type. Variables as a reference value are given a reference or a pointer to that value. The variables don’t actually store the value.
  • Objects in JavaScript may be defined as an unordered collection of related data or primitive or reference types, in the form of “key: value” pairs. These keys can be variable or functions and are called Properties and Methods, in the context of an object.
  • In JavaScript, Objects are king which means if you understand objects, you can understand JavaScript.
  • In JavaScript, almost ‘Everything’ is an object. Boolean, numbers, and string can also be objects. (If defined with “new” keyword)
  • Dates, Maths, Regular expressions, Arrays Functions, and Objects are always objects in JavaScript.

i. JavaScript Variables

JavaScript variables can contain single values.

Example-

var person = “Daniel Johnson”;

Objects are variables too. But, objects can contain many values. The values are written as name: values pairs (name and value separated by a colon).

Var Person = {firstName : “Daniel”, lastName : “Johnson”, age= 40, eyecolor = “black”};

ii. JavaScript Object Properties

A JavaScript object has properties with it. A property of an object can be explained as a variable that can be attached to the object. Object properties are basically the same as ordinary JavaScript variables, except for the attachment to objects. The properties of an object define the characteristics of the object.

Example – objectName.propertyName

Like all JavaScript variables, both the object name ( which could be a normal variable) and property name are case sensitive.

Example – let’s create an object named myCar and give it properties named make.model and year as follows:

Var.myCar = newObject();
myCar.make = ‘Ford’;
myCar.model = ‘Endeavour’;
myCar.year : '2010'

myCar.Color;

Example – You could access the properties of the myCar object as follows:

myCar[‘make’] = ‘Ford’;
myCar[‘model’] = ‘Endeavour’;
myCar[‘Year’] : 2010;

However, any property name that is not valid JavaScript identifier( for example – a property name that has space or hyphen, or that starts with a number) accesses using square bracket notation, only.

Example –

var myObj = new Object();
str = “mystring”;
rand = Math.random();
obj= new Object();
myObj.type = ‘Dot syntax’;
myobj[‘date created’] = ‘String with space’;
myObj[str] = ‘String value’;
myObj[rand] = ‘Random Number’;
myObj[obj] = ‘object’;
myObj[ ‘ ‘] = ‘Even an empty string’;
console.log(myObj);

When the key obj is added to The myObj, JavaScript will call the obj.toString() method, and use this resulting string as the new key.

iii. Deleting JavaScript Object Properties

By using the delete operator, you can remove an object.

// It will create a new object, myObj with two properties a and b
var myObj = new Object;
myObj.a = 10;
myObj.b = 20;
//remove the a property leaving myObj with only the b property
delete myObj.a;
console.log(‘a’ in myObj);//yields “false”

You can also make use of delete to delete a global variable.

g = 17;
delete g;

iv. JavaScript Objects are Mutable

Objects are mutable. They are addressed by reference, not by value.
If a person is an object, the following statements will not create a copy of person.

Example –

var x = person;

It is person. Both x and person are the same objects.

Example –

var person ={ firstName : “Daniel”, lastName : “Johnson”, age : 50, eyecolor =”blue”}
Var x = person;
x.age =10;

v. Data Types of JavaScript Objects

There are three data types of JavaScript objects:

a. String Objects

Generally, strings are created as primitives: var firstName = “Daniel”
And also, strings can also be created as objects using the new keyword. var firstName = new String(“ Johnson”)

b. Number Objects

Normally, numbers create as primitives var x = 44. But, the number can also create as objects using the new keyword: var x = new Number(44).

c. Boolean Objects

Normally, booleans create as primitives: var x = true. But, boolean can also create as objects using the new keyword: var x = new Boolean(true);

vi. Comparing JavaScript Objects

In JavaScript, objects are a reference type. Two objects cannot be equal even if they have the same properties. If you compare the same object properties with itself then it will yield true.

Example –

var fruit = {name : ‘apple’};
var fruitbear = {name: ‘apple’};
fruit ==fruitbear; //return false
fruit===fruitbear; //return false
// two variables, a single object
var fruit = {name: ‘apple’};
var fruitbear = fruit; //assigns fruit object reference to fruitbear
fruit == fruitbear; //return true
fruit ===fruitbear;//return true
fruit.name = ‘grape’;
console.log(fruitbear);//yields { name : “grape”} instead of {name. “apple”}

Explore JavaScript Syntax and Implementation of JavaScript Code

2. How to Create Objects in JavaScript

JavaScript has a number of predefined objects. In addition, you can create your own objects. Alternatively, you can first create a constructor function and then instantiate an object invoking that function in conjunction with the new operator.

i. Using Object Initializers

In addition to creating objects using a constructor function, you can create objects using an object initializer.
The syntax for an object using an object initializers is:

Var obj = { property_1: value _1,
2: value_2,

//…,
‘property n’: value_n};

The following example creates mySuzuki with three properties. Note that the Engine Property is also an object with its own properties.

Example –

var mySuzuki= {color : ‘red’, wheels : 4, Engine: { cylinders:4, size:2.2};

We can also use object initializers to create JavaScript Objects array.

ii. Using Constructor Function

Object creation can be done in two ways:

  • You can define the object type by writing a constructor function. There is a strong convention, with good reason, to use capital initial letters.
  • You can create an instance of the object with new.

To define an object type, create a function for the object that specifies its name, properties and methods.

Example – create an object of type Car and have properties for make, model and year.

Object initializers are an expression, and each object initializer results in a new object being created whenever the statement in which it appears is executed. Objects are also created as if a call to new Object() were made; that is, object made from object literal expression are instances of the object.

The following statements create an object and assign it to the variable x if and only if the expression cond is true.

If (cond) var x = { greeting : ‘hello there’};

Example –

function Car (make, model, year) {
this.make = make;
this.model = model;
this. Year = year;
}

Note that use of this to assign values to the object properties based on the values passed to the function.

The myCar object creates as follows:

Example –

var myCar = new (‘Eagle’, ‘Talon TSI’, 1963);

iii. Using Object Literal

This is the easiest way to create a JavaScript object using object literal, you both define and create an object in one statement.

An object literal is a list of name: value pairs inside the curly braces.

Create a new JavaScript object with four properties.

Example –

var person = { firstName : “John”, lastName : “Doe”, age :50, eyecolor : “blue};
Spaces and line breaks are not important. An object definition can span multiple lines.
Ex: var person = {
firstName =”John”;
lastName = “Doe”;
age: 50;
eyecolor: “blue”;
};

iv. Using JavaScript Keyword ‘new’

With four JavaScript properties, the following example creates a new object:

Example –

var person = new object()
person.firstName = “John”;
person.lastName = “Doe”;
person.age = 50;
person.eyecolor = “blue”;

v. New Object Creation in ECMA Script 5

It is also known as ES5 and ECMA Script 2009.

a. New Object Property Method

Object.defineProperty() is a new object method in ES5.

//create an object
Var person = {
firstName : “John”,
lastName : “Doe”,
language : “No”,
}

b. Change a Property

Object.defineProperty(person, “language”),{
Value : “EN”,
Writable: true,
Enumerable: true
});
//enumerate properties
var txt = “”;
for (var x in person){
txt += person[x] + “<br>”;
}
Document.getElementById(“demo”).innerHTML= txt;

ECMA Script 5 added a lot of methods to JavaScript

c. ES5 New Object Methods

// adding or changing an object property
Object.defineProperty(object, property, descriptor)
//adding or changing many object properties
Object.defineProperties(object, descriptors)
//Accessing properties
Object.getOwnpropertyDescriptor(objects, property)
//return all properties as an array
Object.getOwnPropertyNames(object)
//return Enumerable properties as an array
Object.keys(object)
//Accessing prototype
Object.getPrototypeof(Object)
Object.isExtensible(object)
//prevents changes of object properties
Object.seal(object)
//returns true if object is sealed
Object.isSealed(object)
//prevents any changes to an object
Object.freeze(object)
//returns true if object is frozen
Object.isFrozen(object)

Don’t forget to explore JavaScript Features.

3. JavaScript Object Methods

Methods are the functions that work on objects. There is also a small difference between a function and a method – a function is a standalone unit of statements and a method is attached to an object and can be referenced by this keyword.

Example –

<html>
<head>
<title> user – defined objects </title>
<script type = “text/javascript”>
// define a function which will work as a method
function addprice(amount) {
this.price = amount;
}
function book (title, author){
this. Title = title;
this.author = author;
this.addPrice = addPrice;
}
</script>
</head>
<body>
<script type = “text/javascript”>
Var myBook = new book(“Perl”, “Robert”);
myBook.addPrice(100);
document.write(“Book title is: “+ myBook.title+ “<br>”);
document.write(“Book author is : “+myBook.author + “<br>”);
document.write(“Book Price is : “+myBook.price + “<br>”);
</script>
</body>
</html>

Output:

Book title is: Perl

Book author is: Robert Book price is: 100

i. User-defined Objects and the New Operator

  • All user-defined objects and built-in objects derive from an object called Object.
  • The new operator creates an instance of an object.
  • New object creates using the constructor method.

In the following example, constructor methods are Object(), Arrays(), and Date(). These constructors are built in JavaScript functions.

Example –

var employee = new Object();
Var books = new Array (“C++”; “Perl”, “Java”);
Var day = new Date( “February 25, 2019”);

ii. JavaScript Object() Constructor

A constructor is a function that creates and initializes an object. JavaScript provides a special constructor function called Objects() to build the Object. The assigned variable will get the value returned by Object() constructor.
The variable contains a new object’s reference. The properties of the object are not variables and are not defined with the var keyword.

Example –

<html>
<head>
<title> used -defined objects </title>
<script type = “text/javascript”>
Var book = new Object();
book.subject = “Perl”;
book.author = “Robert”;
</script>
</head>
<script type = “text/javascript”>
Document.write (“Book name is :”+ book.subject + “<br>”);
Document.write(“book author is +”book.author +”<br>”);
</script>
</body>
</html>

Output:

Book name is: Perl

Book author is: Robert

You must learn the advantages & disadvantages of JavaScript.

4. JavaScript Prototype

The JavaScript property allows you to add new properties to object constructors. A prototype is an object that associates with every function and object. In that, the function’s prototype property is accessible and modifiable and the object’s prototype property is not visible.

Every function includes a prototype object by default. The prototype object is also a special type of enumerable object to which additional properties can attach to it which will share across all the instances of its constructor function.

Example –

function Student() {
this.name = “John”;
this.gender = ‘M’;
}
Student.prototype.age = 15;
Var studObj 1 = new student();
alert(studObj 1.age); //15
var studObj. 2 = new Student();
alert (studObj2.age); //15

Example –

function Student() {
this.name = “John”;
this.gender = “M”;
}
Var studObj = new Student();
console.log(Student.prototype); //object
console. log(studObj.prototype); //undefined
console.log(studObj._proto_); //object
console.log(typeof Student.prototype); //object
console.log(Student.prototype ===studobj+_proto_); //true

As you can see in the above example, the function’s prototype property accesses using <function_name> prototype.

Note – The prototype property is a special type of enumerable object which cannot iterate using for .. in or for .. each loop.

i. Object’s Prototype

The object’s prototype property is invisible.

Example –

Object Prototype
function Student() {
this.name = “John”,
this. gender = “M”;
}
var studObj = new Student();
Student.prototype.sayHi = function () {
alert(“Hi”);
};
var studObj 1= new Student;
var proto = Object.getPrototypeof(studObj1);
alert(proto.Constructor);

The prototype object includes the following properties and methods:

  • Constructor – It returns a function that creates an instance.
  • hasOwnProperty() – Returns a Boolean indicating whether an object contains the specified property, a direct property of that object and not inherited through the prototype chain.
  • prototype() – Returns a Boolean indicating whether the object is in the prototype chain of the object this method is called upon.
  • toLocaleString() – Returns string in Local format.
  • toString() – returns string.

ii. Changing Prototype

If you change the function’s prototype, then only new objects will link to prototype. All other existing objects will still link to add prototype of the function.

Example –

function Student() {
This.name : “John”;
This.gender : “M”;
}
Student.prototype.age = 15;
Var studObj 1 = new Student();
Alert( ‘studObj1.age = ‘+ studObj1.age); //15
Var studObj 2 = new Student();
Alert ( ‘studObj 2.age =’+ studObj2.age); //15
Student.prototype = {age :20};
Var studObj. 3 = new Student();
Alert(‘studObj3.age = +studObj3.age); //20
Alert (‘studObj1.age =’+studObj1.age); //15
Alert(‘studObj2.age = ‘+studObj2.age); //15

iii. Uses of Prototypes

The JavaScript engine uses Prototype in two things:

  • To find properties and methods of the object.
  • To implement inheritance in JavaScript.

Example –

function Students() {
this.name = “John”;
this.gender = “M”;
}
Students.prototype .sayHi = function(){
Alert (“Hi”);
};
var studObj = new Student();
studObj.toStrings();

In the above example, the toString() method is not defined in student, so how and from where it finds toString()?

Here, prototype comes into picture. First of all, JavaScript engine checks whether toString() method is attaches to studObj. If it does not find these it uses studObj’s _proto_ link which points to the prototype object of Student function. If it still cannot find it there then it goes up in the hierarchy and checks the prototype object of object function because all the objects derive from Objects in JavaScript and look for the toString() method.

Thus, it finds toString() method in the prototype Obj of Object function and so we can call a stud.Obj.toString().
This way prototype is keeping one copy of functions for all the objects.

You must know the JavaScript Architecture.

5. Getters and Setters Function

Using getter function, we can get the specific value of the property. A setter is a method that sets the value of the specific property. You can define getters and setters on any previously defined object or user-defined object that maintains the addition of new properties. The syntax defines getters and setters using the object literal syntax.

The following example shows how getters and setters could work for a user-defined object o:

Example –

var o = {
a : 8;
get b() {
return this.a +1;
},
set c(x) {
this.a = x/2;
}
};
console.log(o.a); //8
console.log(o.b); //9
o.c =80;
console.log(o.a);//40

The o object properties are :

  • o.a – a number
  • o.b – a getter that returns o.a plus 2
  • o.c – a setter that defines the value of o.a to half the value.

You should be aware that function names of getters and setters define in an object literal by using “[gs] et property()”. Naming a function in a getter or setter using the “[gs]et property ()” syntax, sets function programmatically by using object.defineProperty.

The following code shows how getters and setters can extend the date property to add a year property to all instances of the predefined date class.

These statements state a getter and setter for the year property.

Example –

var d = Date.Prototype;
Object.defineproperty(d, ‘year’, {
get: function() { return this.getFullYear();}
set: function(y) { this.setFullYear(y);)
});

Using getter and setter method
var now = new Date() ;
console.log(now.year);
now.year = 2001;
console.log(now);

In principle, getter and setter can be either

  • Defined using object initializer or
  • The setter part adds to any object at any time using a getter or setter adding method.

When defining getters and setters using object initializers all you need to do is to prefix a getter method with getter and setter methods with a set, of course, the getter method must not expect a parameter, while the setter methods expect exactly on the parameter.

Example –

var o = {
a : 8,
get b() { return this.a + 1};
set c(x) { this.a = x/2}

Using the getter and setter method, objects add to the Object.defineProperties method. This method’s first parameter is the object on which you want to define the getters or setter. A second parameter is an object whose property names are getter or setter names, whose property values are objects for defining the getter or setter function.

Example –

var O ={ a: O};
Object.defineProperties(O, {
‘b’ : { get :function () { return this.a +1}
‘c’: { set : function() { this.a = x/2}}
});
O.c = 10; //runs the setter
console.log(O.b);

Grow your career in JavaScript.

6. Summary

In this article, we have gone through how to create JavaScript objects, their properties, and how to create an object, JavaScript object methods, new object creation in ECMA Script 5, prototypes in JavaScript and getters and setters function.

If you have any questions or feedback related to the article, feel free to share with us in the comment section.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.