How can I call PrintIt foo from Set()? I get error that it can't find it...
I know it's possible to call it via MyObject.prototype.PrintIt but this way i will "lose" the object and it's property (Num)
MyObject = function(){
this.Num=6;
}
MyObject.prototype = {
initialize: function(){
document.getElementById("button1").onclick = this.Set;
},
Set: function(){
this.PrintIt();
},
PrintIt: function(){
alert("I Print");
//alert( this.Num);
}
}
window.onload = function(){
obj = new MyObject;
obj.initialize();
}
How can I call PrintIt foo from Set()? I get error that it can't find it...
I know it's possible to call it via MyObject.prototype.PrintIt but this way i will "lose" the object and it's property (Num)
MyObject = function(){
this.Num=6;
}
MyObject.prototype = {
initialize: function(){
document.getElementById("button1").onclick = this.Set;
},
Set: function(){
this.PrintIt();
},
PrintIt: function(){
alert("I Print");
//alert( this.Num);
}
}
window.onload = function(){
obj = new MyObject;
obj.initialize();
}
Share
Improve this question
edited Nov 10, 2010 at 8:44
Felix Kling
818k181 gold badges1.1k silver badges1.2k bronze badges
asked Nov 10, 2010 at 8:36
shlomjmishlomjmi
6973 gold badges12 silver badges16 bronze badges
0
1 Answer
Reset to default 7The problem lies not in the prototype but in the way how you assign the method to the click handler. There it loses its connection to the object. You can use a closure:
initialize: function(){
var that = this;
document.getElementById("button1").onclick = function(){
that.Set();
};
},