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).
Deleting JavaScript Properties and Methods - Properties and Methods Belonging Only to a Particular Object (Page 3 of 5 )
In this section we shall see how to delete a property or a method that belongs to an object (instance). Add the following code at the bottom of the above script.
function investigate()
{
answer = delete theObject.property1;
alert('Boolean result is ' + answer );
alert(theObject.property1); //try the property
}
Remove the HTML buttons and replace them with the following:
For all the browsers, the operation returned true and displayed the value "undefined" for the property after deleting. So the first alert box displayed “Boolean result is true.” The second one displayed “undefined.” Go through the code to understand what happened if you have not already done so.
Let us check to see if the method can be deleted. Replace the statements in the investigate() function with the following:
answer = delete theObject.method1;
alert('Boolean result is ' + answer );
theObject.method1(); //try the method
The alert box has to display the returned Boolean value. If the method is still there after the delete process, we should see an alert box displaying “This is function one.”
I tested the code with all five browsers; the Boolean return value was true. When the method was called after the delete operation, nothing happened. This definitely means the method was deleted.
So a property or method that belongs to an object can be deleted.