When you call greeting.greet()
, this.greeting
is undefined
, thus the problem.
Explanation:
Try this code:
var Greeter = (function () {
function Greeter(message) {
this.greeting = message;
}
Greeter.prototype.greet = function () {
return "Hello, " + this.greeting;
};
return Greeter;
})();
console.log('Log 1: ' + Greeter);
var Greeting = (function(){
console.log('Log 2: ' + Greeting);
Greeting.prototype = new Greeter();
console.log('Log 3: ' + Greeting);
Greeting.prototype.constructor = Greeter;
console.log('Log 4: ' + Greeting);
function Greeting(greeting){
}
console.log('Log 5: ' + Greeting);
return Greeting;
})();
console.log('Log 6: '+Greeting);
var greeting = new Greeting("World");
alert(greeting.greet());
You will see that Greeting
is just an empty function, but with Greeter
as the prototype. So, new Greeting('World')
creates the following function:
function Greeting(greeting){
}
with a prototype containing greeting
(undefined), constructor
(a function), and greet
(a function). Greeting.prototype.greet
, in turn, has this definition:
Greeting.prototype.greet = function () {
return "Hello, " + this.greeting;
};
But this.greeting
is undefined in this context, because this
refers to Greeting.prototype.greet
, not Greeter
. Thus, these lines:
var greeting = new Greeting("World");
alert(greeting.greet());
fail, because greeting.greet()
returns Hello,
concatenated with an undefined value.