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 - Deleting Properties and Methods (Page 2 of 5 )
There is an operator called the delete operator. The specification says this operator can delete an object’s property. It does not say whether or not it can delete a method. The specification also says that it can delete user-defined property.
We have to carry out our own investigations to learn whether it can delete a method that belongs only to one object; whether it can delete a property or a method that belongs to all objects (object type); and whether it can delete a property or method in the object type constructor function. It is not clear from the specification if we can achieve this.
I used Internet Explorer, Mozilla Firefox, Netscape, Opera and Safari to carry out these investigations. I give you the results in this section. The syntax to delete a property is:
delete objectName.property
This operation returns true if it succeeds in deleting the property. It returns false if it does not succeed in deleting the property. If the delete operator succeeds, it sets the property or element to undefined (that is what is in the specification).
We shall use the above code for our investigations. Our test for the three cases is simple: we shall attempt to delete a property or method, and then display the returned Boolean value. If the Boolean value returned from the operation is true for all the browsers, then it means the property or method was deleted. To really be sure, we shall try to display the value of the deleted property or execute the method.