Compile Time and Run Time
Just before the web page is displayed, the objects, properties and methods are created at compile time. When the web page is displayed, any object, property or method is created (while you are working on the page) at run time. The properties and methods we added in the first and second parts of the series have been created at compile time.
Adding and Deleting Properties and Methods at Run Time
Adding Properties and Methods at run time
To add or delete a property or method at run time, you have to add or delete the property or method after the page has been loaded. To achieve this, we shall put an HTML button on the web page that has an object. When this button is clicked, the property or method will be added.
Let us use the following code:
alert('This is function type one');
alert('This is function type two');
alert('This is function one');
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;
<button type="button" onclick="runTimeFn()">Add Properties and Methods</button>
Let us look at the code from top to bottom. The functionType1() function is for the method in the object type constructor function. This function and its method are created at compile time. The functionType2() and function1() functions shall be methods of the object at run time. The method for functionType2() will be for the object type, while the method for function1() will be for the object (inherited).
Next you have the constructor function for the object type. This object type and its property and method are created at compile time. After that we have a function definition. This is the function that is called when you click the button.
The first two statements in this function add a property name and a method name to the object type respectively. The next statement creates an object. The next two statements assign values to the property and method of the object for the “unassigned” property and method added to the object type.
The two statements following that add a property and a method only to the particular derived object. The remaining four statements display the values of the properties added and call the methods; an alert box should be displayed ultimately by each of these statements. You can save the above code as an HTML file, and then open it in your web browser and try it (click the button).
This section has shown you how to add properties and methods at run time.