Reputation: 39
I know there are several ways to create Objects, add Methods and Properties etc. There is one thing I don't understand about prototypes
function Obj () {
var msg = "message";
this.log = function (){
console.log(msg);
}
}
var o = new Obj();
o.log();
this would output message. however using a prototype
function Obj2 () {
var msg = "message2";
}
Obj2.prototype.log = function () {
console.log(msg);
}
var o2 = new Obj2();
o2.log();
would output that msg is not defined. why is that?
Upvotes: 0
Views: 36
Reputation: 7666
You have a scope problem as mentioned by @Quentin, However if you need to access the variable inside the prototype function, you need to make use of this and treat it as a class. So now it will be treated as a property to the class Obj2 and not as a private variable.
So the code will be like:
function Obj2 () {
this.msg = "message2";
}
Obj2.prototype.log = function () {
console.log(this.msg);
}
var o2 = new Obj2();
o2.log();
Upvotes: 0
Reputation: 944568
msg
is a variable that is scoped to Obj
and Obj2
respectively.
The log
function in the first example is defined within the scope of Obj
so it has access to variables from that scope.
The log
function in the second example is not defined within that scope of Obj2
, so it doesn't.
Upvotes: 1