Get in touch
or send us a question?
CONTACT

[Node.js Tutorials for Beginners] – Unit 6: Objects in Node.js

thumbnail

Table of Contents

1. Create an object

2. Object Properties

3. Object Methods

4. Some example

5. Global Objects

1. Create an Object

To create an object, we can use either of the following:

var obj1 = new Object();

var obj2 = {};

The latter, known as object literal syntax, is preferred.

We can specify the contents of objects using object literal syntax.

We can specify member names and values at initialization time:

2. Object Properties

The syntax for adding a property to an object is:

objectName.objectProperty = propertyValue;

For example: The following code gets the user address using the “address” property of the user object.

var str = user.address;

3. Object Methods

Methods are the functions that let the object do something or let something be done to it. There is a small difference between a function and a method – at a function is a standalone unit of statements and a method is attached to an object and can be referenced by the this keyword.

Methods are useful for everything from displaying the contents of the object to the screen to performing complex mathematical operations on a group of local properties and parameters.

For example: Following is a simple example to show how to use the write() method of user object to write any content on the user.

user.write(“This is test for write function”);

4. Some Example

var user = {

    first_name: “Manh”,

    last_name: “DK”,

    age: 32,

    username: “ManhDK”

};

We can add a new property to your user object by using any of the following methods:

user.address = “Vinh”;

user[“address”] = “Vinh”;

var attribute = ‘address’;

user[attribute] = “Vinh”;

If we try to access a property that does not exist, we do not receive an error, but instead just get back undefined.

To remove a property from an object, we can use the delete keyword:

delete user.address

5. Global Objects

Node.js global objects are global in nature and they are available in all modules. We do not need to include these objects in our application, rather we can use them directly. These objects are modules, functions, strings and object itself as explained below.

__filename

The __filename represents the filename of the code being executed. This is the resolved absolute path of this code file. For a main program, this is not necessarily the same filename used in the command line. The value inside a module is the path to that module file.

Example: typing the following code in the unit6.js file

console.log(__filename);

Now run the unit6.js to see the result

$ node unit6.js

Based on the location of your program, it will print the main file name as follows

/home/manhdk/nodejs/unit6.js

__dirname

console.log(__dirname)

setTimeout(cb, ms)

clearTimeout(t)

setInterval(cb, ms)

Thank you for reading!