power = function(a, b)
{
return Math.pow(a,b);
}
return methods;
}
var sm = new SimpleMath();
alert(sm.power(5,6));
This example declared some core methods outside of the SimpleMath object. These core
methods can stand alone or be applied to another object in addition to being applied to the
SimpleMath object defined here.
The following shows another object that inherits the same core methods while still
extending it with its own methods. It??™s a Pizza object that can be instantiated with the number
of slices. You can then split the pizza up among friends, which automatically uses the divide
method from the core methods:
var Pizza = function(slices)
{
var methods = coreMethods;
methods.split = function(friends)
{
return methods.divide(slices,friends);
}
return methods;
}
var za = new Pizza(16);
alert(za.split(4)); // alerts "4"
CHAPTER 3 n OBJECT-ORIENTED PROGRAMMING 61
Prototype
JavaScript is called a prototype-based language (as opposed to a class-based language)
because inheritance is handled through prototype chaining. In the previous examples, each
new object that gets instantiated copies the new property and method onto each object. If
you have 1,000 objects, there would be 1,000 properties and methods??”each holding a special
place in memory.
To avoid this overhead, there is a prototype property on which you can attach methods
that are meant to be shared across all objects:
var Adder = function(valueA, valueB){
var newvalue = valueA + valueB;
this.
Pages:
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117