在原型对象中调用函数

shl*_*jmi 4 javascript

如何从Set()调用PrintIt foo?我得到它无法找到它的错误...
我知道可以通过MyObject.prototype.PrintIt调用它但这样我将"丢失"对象及其属性(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();                                
}
Run Code Online (Sandbox Code Playgroud)

Fel*_*ing 7

问题不在于原型,而在于如何将方法分配给点击处理程序.它失去了它的对象连接.你可以使用一个闭包:

initialize: function(){
    var that = this;     
    document.getElementById("button1").onclick = function(){
        that.Set();
    };
},
Run Code Online (Sandbox Code Playgroud)