CancelImage Upload

How to create and initialise a new object with JavaScript

Although maybe not as object orientated as other programming languages, JavaScript does allow you to initiate and make use of your very own object. To do this all that you require is a simple function. In our example we will use a function called newUser(), where new users can be added and initiated:

function newUser(firstname, surname, from)
{

        this.firstname = firstname;

        this.surname = surname;

        this.from = from;

}

To initiate an object based on this function we will use the following code. The two new objects will be named nU1 and nU2 (new user 1 and 2):

nU1 = new newUser("Mark", "Johnson", "London");

nU2 = new newUser("John", "Grey", "Birmingham");


Now that these two objects have been created, we can access the various user details that we have specified through them:

var dU1 = document.getElementById("user1");

var dU2 = document.getElementById("user2");

dU1.innerHTML = nU1.firstname + " " + nU1.surname + " from " + nU1.from;

dU2.innerHTML = nU2.firstname + " " + nU2.surname + " from " + nU2.from;

As you can see there is nothing to it. Here is what you get when you put all the above code together:

<html>
<head>
<title>How to create and initialise a new object with JavaScript</title>
<script type="text/javascript">

function newUser(firstname, surname, from)
{

        this.firstname = firstname;

        this.surname = surname;

        this.from = from;

}

function load()
{

        nU1 = new newUser("Mark", "Johnson", "London");

        nU2 = new newUser("John", "Grey", "Birmingham");

        var dU1 = document.getElementById("user1");

        var dU2 = document.getElementById("user2");

        dU1.innerHTML = nU1.firstname + " " + nU1.surname + " from " + nU1.from;

        dU2.innerHTML = nU2.firstname + " " + nU2.surname + " from " + nU2.from;

}
</script>
</head>

<body onload="javascript:load();">

<span id="user1"></span><br>
<br>
<span id="user2"></span>

</body>
</html>


Login
Want to leave a comment?

No problem. Just enter your email and password below.


register | home | reminder

myDesignTool Networking • www.mydesigntool.cominfo@mydesigntool.com