Here is an example of how to create custom objects and properties using the
Constructor Function.
Usually you can get by with using JavaScript's built-in objects, built-in properties and built-in methods. But imagine the power in creating your own!
A few things to remember about constructor functions:
- Constructor Function names usually begin with a capital letter (but not always!).
- Variables defined within the function body use the "this" keyword. These variables become properties of any new object that is based on the function.
function Table(){
this.tableOpen = "<table>"
this.trOpen = "<tr>"
this.text = "This table was created with JavaScript"
this.tdClose = "</td>"
this.trClose = "</tr>"
this.tableClose = "</table>"
}
- Constructor functions can be extended in two places: to another function or to a new object. In both cases, the extended objects inherit the properties of the function it extended.
- When extending to another function so that the new function has access to another function's properties, use this syntax:
function GreenTd() {
this.tdOpen = "<td bgcolor=\"green\">"
}
GreenTd.prototype = new Table()
- When extending to a new object, use this syntax:
GreenTable = new GreenTd()
- To reference the properties, append the object name with a period followed by the property name:
GreenTable.tableOpen
GreenTable.trOpen
Then write it to the page:
document.write(GreenTable.tableOpen)
document.write(GreenTable.trOpen)
Now lets add an argument
View the Source