Adding and Deleting JavaScript Properties and Methods
Did you know that after you have written the code for a JavaScript object, you could still add properties and methods to the object at run time? Did you know that the user can add properties and methods to a JavaScript object? In this three part series, I show you how to add JavaScript properties and methods at compile and at run time.
Adding and Deleting JavaScript Properties and Methods - Adding without passing parameters (Page 2 of 4 )
For simplicity, we shall consider the case where the function creating the object does not have parameters.
Example
Let us consider an example where the object type has one property and one method. The name I give to the object is ObjectType. The value of the property of the object type is:
"Yes Type One"
The function to be used as the method of the object type is:
function functionType1()
{
alert('This is function type one');
}
To create a particular object (instance) from the object type you use the new operator. I call the particular object I created from the object type, theObject. So we have
var theObject = new ObjectType();
The object type itself is created using the constructor function. We have for the object type,
function ObjectType()
{
this.propertyType1 = "Yes Type One";
this.methodType1 = functionType1;
}
You can use the following sample to try out what we have described so far in this section.
<html>
<head>
<script type="text/JavaScript">
function functionType1()
{
alert('This is function type one');
}
function ObjectType()
{
this.propertyType1 = "Yes type one";
this.methodType1 = functionType1;
}
var theObject = new ObjectType();
</script>
</head>
<body>
<button type="button" onclick="alert(theObject.propertyType1)">Display property type 1</button>
<button type="button" onclick="theObject.methodType1()">Call Method type 1</button>
</body>
</html>
This is a small web page. There are two buttons. When you click the first button, the value of the property for the type "object" is displayed. When you click the second button, the method for the type "object" is called.