I'm currently studying javascript prototypes and I'm quite confused on how it really works. I have this code snippet and it works perfectly
function Message(msg){
this.msg =msg;
}
Message.prototype = {
constructor:Message,
display: function(){
return this.msg;
}
};
alert(new Message("007").display());
What this code is trying to do is to illustrate a simple encapsulation by using javascript.
Now the problem is, I want to add this text:this.msg instead of using the display method
Message.prototype = {
constructor:Message,
someValue:99,
text: this.msg,
display: function(){
return this.msg;
}
};
But i only get undefined when i call
alert(new Message("007").text);
But calling
alert(new Message("007").someValue);
Displays 99. What is the problem here?
At the time the prototype is being declared, it sees the line text: this.msg,
and assigns its text
property to the value of its this
's msg
property. But the this
at that point refers to the global/window object - whose .msg
property is undefined.
On the other hand, when display
is called, the instantiated object has had its constructor run, so the msg
property of the instantiated object has been populated, and display
is run with the expected calling context. (where this
is the instantiated object) Just keep using the display
property.
(Also, you don't define the constructor in the prototype: just leave off the constructor:
line entirely in the prototype)