4

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();                                
}
0

1 Answer 1

7

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();
    };
},
4
  • I always forget about closure... Is there a "rule of thumb" for that?
    – shlomjmi
    Commented Nov 10, 2010 at 9:17
  • @shlomjmi: You mean when to use it? Whenever you assign a method, but want to execute the method in the object's context. But this practice will probably disappear, when bind() is more supported: developer.mozilla.org/en/JavaScript/Reference/Global_Objects/… Commented Nov 10, 2010 at 9:21
  • Well I can't get it for 100% when I must use closure, I know for exaple that closure is used wen assigning events in a loop... (otherwise only the last index will be assigned)
    – shlomjmi
    Commented Nov 10, 2010 at 9:24
  • 1
    @shlomjmi: If you understand how JavaScript works, then you will know when to use closures ;) Or whenever you are wondering why something does not work, remember closures, maybe they help :) Commented Nov 10, 2010 at 9:24

Not the answer you're looking for? Browse other questions tagged or ask your own question.