Introduction
In this article we will learn about objects in JavaScript. Everything in JavaScript is an object. In addition, JavaScript allows us to define our own objects. So, when we code in JavaScript we can call each and every single token an object.
- Arrays are always objects, even functions are always objects
- Dates are always objects
- Booleans can be objects or primitive data treated as objects
- Numbers can be objects or primitive data treated as objects
- Strings are also objects or primitive data treated as objects
- Maths and RegularExpressions are always objects
Let's see how to define an object and set a property on that.
Open the Notepad++ editor and write the following code:
- <!DOCTYPE html>
- <html xmlns="http://www.w3.org/1999/xhtml">
- <head runat="server">
- <title></title>
- </head>
- <body>
- <form id="form1" runat="server">
- <script>
- var obj = new Object();
- obj.name = "csharp";
- obj.lastname = "corner";
- alert("Name:- " + obj.name + " Lastname:- " + obj.lastname);
-
- </script>
-
- </form>
- </body>
- </html>
In JavaScript we can create an object and set a property on fly. Here is sample output of the program above.
Now let's see how to initialize the object using constructor. Have a look at the following code.
- <!DOCTYPE html>
- <html xmlns="http://www.w3.org/1999/xhtml">
- <head runat="server">
-
- </head>
- <body>
- <form id="form1" runat="server">
- <script>
- function samplefunction(name, lastname) {
- alert(name +" " +
- lastname);
- }
- var value = new samplefunction("Csharp", "corner");
- </script>
- </form>
- </body>
- </html>
In the code above we declared a function called “samplefunction” and takes two parameters. In the next line we are creating one object of the “samplefunction” function and at the time of creation we are passing two parameters into it. Here is the sample output.
Now let's attach a function to an object in JavaScript. In the following example we will see how to do that. Have a look at the following code.
- <!DOCTYPE html>
- <html xmlns="http://www.w3.org/1999/xhtml">
- <head runat="server">
-
- </head>
- <body>
- <form id="form1" runat="server">
- <script>
-
- var xyz = new Object();
- xyz = function ()
- {
- alert("xyz function");
- }
- xyz();
-
- </script>
- </form>
- </body>
- </html>
Summary
In this article we learned how to define an object in JavaScript. In a future article we will learn some more basic concepts of JavaScript.