最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Calling function within prototype object - Stack Overflow

programmeradmin1浏览0评论

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
Add a ment  | 

1 Answer 1

Reset to default 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();
    };
},
发布评论

评论列表(0)

  1. 暂无评论