Reputation: 697
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();
}
Upvotes: 4
Views: 4320
Reputation: 816302
The 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();
};
},
Upvotes: 7