JavaScript Prototype Property
With the prototype property it is possible to add properties and methods to an object. In a similar manner to other languages such as PHP and Java, prototyping allows objects to inherit, override, and extend functionality. Prototyping is best illustrated with an example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 | <!DOCTYPE HTML> <html lang="en-US"> <head></head> <script> // add a base object (functions are objects in JavaScript) var base = function() {} //Add a multiply function to base using prototype base.prototype.multiply = function(a,b){ return a*b;} /* we could also write this using object literal notation base.prototype = { multiply: function(a,b){ return a* b; } } */ //Add a property to base base.prototype.message = "hello from base"; /* we could do this in object literal notation but we need to use __proto__. However, this may not be supported in all browsers. base.__proto__ = { message: 'hello from base' } */ var obj = new base(); alert(obj.multiply(3,5)); // 15 //Access message property added to base alert(obj.message); // hello from base |
Inheritance
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | // Inherit from base by doing the following: //create a new object with a variable 'constant' var calc = function(){ this.constant = 10; } /* allow calc to access all of base's properties and methods by assigning a new base instance to calc's prototype property */ calc.prototype = new base(); var c = new calc(); alert(c.multiply(10,10)); // 100 |
Overriding
1 2 3 4 5 6 7 8 9 10 11 | /* override the existing multiply function by defining a new multiply function assigning it calc's prototype property. */ calc.prototype.multiply = function(a,b){ return a*b - this.constant; } var co = new calc(); alert(co.multiply(10,10)); // 90 alert(co.constant); // 10 |