Deleting JavaScript Properties and Methods
(Page 1 of 5 )
Welcome to the second part of a three-part series on adding and deleting JavaScript properties and methods. In this part of the series, we learn how to delete properties and methods. Before we get into that, let us see how to add properties and methods to objects (instances).
Adding Properties and Methods to Objects
In this section I explain how you can add properties and methods to objects; that is, to instances of object types.
This is a code segment showing what we had in the example at the end of the previous part.
function ObjectType()
{
this.propertyType1 = "Yes type one";
this.methodType1 = functionType1;
}
ObjectType.prototype.propertyType2 = null;
ObjectType.prototype.methodType2 = null;
var theObject = new ObjectType();
We have the ObjectType object type, and we have the object derived from it, theObject. You can add properties and methods to the theObject instance. When you do this, the property name, the method name, the property assigned value and the method assigned function will not occur in the object type; they will not occur in other objects (instances) of the object type (class).
After the object has been created with the new operator, to add a property whose value is “Yes one,” you would type,
theObject.property1 = "Yes one";
After the object has been created with the new operator, to add a method to which the function1() function is assigned, you type,
theObject.method1 = function1;
The function1() function should exist in the code.
This is how you add a property or a method that will belong only to the object (instance) concerned. The approach is the same as is would be if you were simply assigning a value or function to a property or method of an object whose property or method had been declared for the object type (as in the last part).
The following code illustrates what we have just learned:
<html>
<head>
<script type="text/JavaScript">
function functionType1()
{
alert('This is function type one');
}
function functionType2()
{
alert('This is function type two');
}
function function1()
{
alert('This is function one');
}
function ObjectType()
{
this.propertyType1 = "Yes type one";
this.methodType1 = functionType1;
}
ObjectType.prototype.propertyType2 = null;
ObjectType.prototype.methodType2 = null;
var theObject = new ObjectType();
theObject.propertyType2 = "Yes type two";
theObject.methodType2 = functionType2;
theObject.property1 = "Yes one";
theObject.method1 = function1;
</script>
</head>
<body>
<button type="button" onclick="alert(theObject.property1)">Display property 1</button>
<button type="button" onclick="theObject.method1()">Call Method 1</button>
</body>
</html>
When you click the first button, the value of the theObject’s only property we have just added is displayed. When you click the second button, the theObject’s only method we have just added is executed.
Next: Deleting Properties and Methods >>
More JavaScript Articles
More By Chrysanthus Forcha