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 - Explanation of the Script (Page 3 of 4 )
The first statement in the script is a function (this is a constructor function, but we are not focusing on its constructive nature). This is the function that is used as the method of the object type (class). Next you have a constructor function. This is the object type.
One way to differentiate between the constructor function, which is an ordinary function and a constructor function, which is an object type, is in the use of the "this" keyword inside the function. In the object type above, "this" refers to the ObjectType() function. You can still use the "this" keyword with ordinary functions, but you will find it used more with object types. Here, ObjectType is the name of the ObjectType() function, which we shall use as an object type.
So, to create the first property in the object type, we have inside it,
this.propertyType1 = "Yes type one";
The property name is propertyType1 and the value assigned is "Yes type one." Note the use of the "this" keyword. The next statement in the constructor function for the object type creates a method for the object type. This is the statement:
this.methodType1 = functionType1;
The "this" keyword refers to ObjectType, which is the name of the function ObjectType(). MethodType1 is the name we have given to the method of the object type. The method function is the function with the name "functionType1." This name is assigned to "method" in the statement.
The function with the name "functionType1" has to exist. We already have it above in the code. Note that you do not have the () brackets attached to the method name above. However, when calling the method, attach the () brackets to the method name.
Next in the code, we create an object with the new operator. This is the statement:
var theObject = new ObjectType();
The name of the particular object created is "theObject." The object type or class is ObjectType. The () brackets are attached to the object type name, since it is a function.
You can save the above code as an HTML file, and then click the buttons to see the results.
Inheritance
Any object such as theObject, created from the object type, inherits the properties and methods of the object type.