Creating User-Defined JavaScript Objects, Properties and Methods - User Created Objects
(Page 3 of 4 )
As you can deduce from the previous page, the user can create objects and add properties and methods to the object. The user has to input the constructor function as a string argument to the eval() function, and that would create the object type. The user can then go on to add properties and methods as we did above. If the user wants to add a method, he has to first use the eval function to create the corresponding function, if the function does not already exist in the code.
Let us now create an object type and object, add a property and a method to the object, and then display the added property and execute the added method, as a user would. We shall use the code segments we have already used before.
Type the following and save as an HTML file.
<html>
<head>
<script type="text/JavaScript">
function userAdd()
{
var evalStr = prompt("Enter the two statements","");
eval(evalStr);
//verify if the property and method were added.
alert(theObject.property1);
theObject.method1();
}
</script>
</head>
<body>
<button type="button" onclick="userAdd()">User Add</button>
</body>
</html>
Open the above HTML file. Looking at the code as it is, when you click the "User Add" button, the statements that you type into the prompt box are enclosed in a string and then assigned to the evalStr variable. The eval() function then evaluates the statements. Next, it is verified whether the property and method were actually added.
We shall put in the statements segment by segment. So until the last segment is input, the verification (last two statements in the userAdd() function) will not give the right result.
Next: Creating User-Created Objects >>
More JavaScript Articles
More By Chrysanthus Forcha