JavaScript - Objects




JavaScript - Objects

Objects in JavaScript, just as in several distinct programming languages, can be linked to objects in real life. The idea of objects in JavaScript can be comprehended with real-life, tangible objects. Today in this JavaScript tutorial series of DataFlair we will explain one of the major topic that is JavaScript Object.

The reason why JavaScript Objects are so important is that JavaScript design depends on a simple object-based paradigm. But unlike C++ or Java, we don’t create any classes. We create objects directly because JavaScript is a template-based rather than class-based. Objects are non-primitive (reference) data types that may contain any combination of primitive as well as reference data types. We can visualize objects as containers that contain properties and methods. JavaScript Objects can easily relate to Real-life Objects like a car, cup, pen, etc.

JavaScript Object

JavaScript is an object oriented language. However, in practice objects defined by the programmer himself are rarely used, except in complex DOM API's. Of course such standard objects as window and document and their numerous offspring are very important, but they are defined by the browser, not by the programmer. I myself have written JavaScript for more than three years without ever defining an object. The technique explained on this page is the first practical use of programmer-defined objects I've found.

Since the only other programming languages I know are Commodore 64 Basic (which is not object oriented, to put it mildly) and Perl (which doesn't need to be object oriented) and since I don't have any formal training in programming I cannot write a general introduction to objects and object oriented programming. Therefore a quick overview will have to suffice.

Methods and properties

In JavaScript you can define your own objects. In addition, you can assign methods and properties to each object, pre-written or self-defined. Methods are 'things that do something', they can be recognized by their brackets (). When you call them, like object.method(), something happens. Properties are 'things that are something'. They have a value, for instance a number, a string or a Boolean value. When you call them, like object.property, you get (or set) this value. Normal JavaScript functions are also methods (hence the brackets). If you do

document.write('text')

you execute the pre-defined write() method of the document object. If you write your own functions you add methods to the window object, the parent of all other JavaScript objects. Likewise, if you ask for the innerHeight of a page, you access a property of the window object and if you define a variable of your own you really add a new property to the window object. So you already use methods and properties in everyday JavaScripting. Since most of these are preprogrammed functions and variables, you usually don't need to worry about the objects themselves, they're just a kind of 'black boxes' that contain useful stuff. The methods and properties (functions and variables) that you define yourself are usually added to the window object.

JavaScript objects are similar to objects in real life which consists of different attributes and properties. These objects are defined as an unordered collection of related data, that are of primitive or reference types. These are defined in the form of “key: value” pairs.

These keys are variables or functions which are called as properties and methods of an object. You can create a JavaScript object as -

let ObjectName = {
Property1 : "Value",
Property2 : "Value",
...
...
}

How to Create a new Object?

There are 3 ways to create a new object - By Object Literal

object={property1:value1,property2:value2.....propertyN:valueN}

Example

<script> 
employee={id:700,name:"Evan",salary:30000}  
document.write(employee.id+" "+employee.name+" "+employee.salary);  
</script>

Output

700 Evan 30000

By Creating instance of Object

var objectname=new Object();

Example

<script>  
var emp=new Object();  
emp.id=701;  
emp.name="Karan";  
emp.salary=40000;  
document.write(emp.id+" "+emp.name+" "+emp.salary);  
</script>

Output

701 Karan 40000

JavaScript is an object-based language and in JavaScript almost everything is an object or acts like an object. So, to work with JavaScript effectively and efficiently we need to understand how objects work as well as how to create your own objects and use them. A JavaScript object is just a collection of named values. These named values are usually referred to as properties of the object.

If you remember from the JavaScript arrays chapter, an array is a collection of values, where each value has an index (a numeric key) that starts from zero and increments by one for each value. An object is similar to an array, but the difference is that you define the keys yourself, such as name, age, gender, and so on. In the following sections we'll learn about objects in detail.

Creating Objects in JavaScript

There are 3 ways to create objects.

  • By object literal

  • By using an object constructor (using new keyword)

  • By creating instance of Object directly (using new keyword)

How to declare Object in JavaScript

Objects in javascript can be declared using curly brackets {}. We can also use new Object() constructor function to declare Objects. Both {} and new Objects() works same. new Object() is constructor form, and curly brackets {} is literal form of JS Objects.

JavaScript Object Literal

  var month={};            // blank Object

JavaScript Object Constructor

var month=new Object();        // blank Object

Javascript is an interesting programming language. Unlike traditional programming languages, it has a prototype-based object system. Here is my attempt to explain the nut and bolts of Javascript language and how its objects work.

Objects

There are many ways to create an object, the simplest form is this -

p = {x:1, y:2};

The properties of the object are accessed using the . notation and new properties can be added at runtime.

a = p.x;     // 1
b = p.y;     // 2
p.z = p.x + p.y; // p.z is 3

Even the primitive objects like numbers work exactly in the same way.

x = 1;
x.newprop = "hello";

Functions

Functions are special objects which are callable.

function square(x) { return x*x; }
square(4); // returns 16

The body of the function has access to two magic variables: this and arguments. A function is always executed in the context of an object, accessible as variable this. The list of arguments passed to the function is accessible as variable arguments. The value of this variable depends on how the function is called. When a function f is called as called as a.f(), the object a becomes the this variable. When called directly as f(), the top-level object becomes the this variable.

Javascript has a top-level object, that maintains the global variables. In the context of web browser, the top-level object is the window object.

The function object has an apply method. Calling square(2) is equivalent to calling -

square.apply(null, [2])

The first argument is the this object and the second one is the list of arguments. When null is specified as first argument, the system uses the top-level object as this.

An example to demonstrate this:

function square_method() {
    return this.value * this.value;
}

var n = {"value": 2};
n.square = square_method;

n.square(); // returns 4
square_method.apply(n, []); // returns 4

var sq = n.square;
sq(); // produces error as this.value is undefined. 

And another simple example to demonstrate arguments -

function count() {
    return arguments.length;
}

count();        // 0
count(1, 2, 3); // 3
count(4, 5);    // 2