Within the function, the this keyword refers to that
object, and you can attach new properties and methods to that object. After your function
is done, that new object is assigned to your variable.
Now you can process information before assigning it to the new object:
var Adder = function(valueA, valueB){
var newvalue = valueA + valueB;
this.value = newvalue;
this.result = function(){ alert(this.value) };
};
var added = new Adder(5, 6);
added.result(); // it's 11!
Returning an Object in the Constructor
You can decide to ignore the this keyword and explicitly return your own object with methods
and properties attached to it:
var Adder = function(valueA, valueB){
var newvalue = valueA + valueB;
var object = new Object();
object.value = newvalue;
object.result = function(){ alert(this.value) };
return object;
};
var added = new Adder(5, 6);
added.result(); // it's 11!
Being able to return an object like this gives you plenty of flexibility, especially when it
comes to handling inheritance. This next example uses an object literal (which will be discussed
in a little bit):
CHAPTER 3 n OBJECT-ORIENTED PROGRAMMING 60
var coreMethods = {
add:function(a, b){
return a + b;
},
minus:function(a, b){
return a - b;
},
multiply:function(a, b){
return a * b;
},
divide:function(a, b)
{
return a / b;
}
};
var SimpleMath = function()
{
var methods = coreMethods;
methods.
Pages:
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116