value = newvalue;
};
Adder.prototype.result = function(){ alert(this.value) };
var added = new Adder(5, 6);
added.result(); // it's 11!
Only the result() method was added onto the prototype. You can??™t add the value property
because it changes depending on the parameters that you pass into the constructor.
Therefore, you have to attach that property at runtime using this.
The prototype property can also be handy because you can add properties to the base
object even after you instantiate new objects. When you do so, those new properties are
also available on the already instantiated objects. Let??™s rearrange that previous example
to demonstrate:
var Adder = function(valueA, valueB){
var newvalue = valueA + valueB;
this.value = newvalue;
};
Adder.prototype.result = function(){ alert(this.value) };
var added = new Adder(5, 6);
added.result(); // it's 11
Adder.prototype.multiply = function(valueC){ alert(this.value * valueC) };
added.multiply(5); // it's 55!
Here??™s how inheritance can be handled:
var Dog = function(){ };
Dog.prototype.bark = function(){ alert('woof') };
var Chihuahua = function(){ };
Chihuahua.prototype = new Dog();
var sparky = new Chihuahua();
sparky.bark(); // woof!
CHAPTER 3 n OBJECT-ORIENTED PROGRAMMING 62
There is shallow inheritance and there is deep inheritance. The example shown here is
considered shallow inheritance. Deep inheritancemeans that you have a class that inherits
from another class that inherits from another class, and so on.
Pages:
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118