简体   繁体   English

原型对象中的调用函数

[英]Calling function within prototype object

How can I call PrintIt foo from Set()? 如何从Set()调用PrintIt foo? 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.prototype.PrintIt调用它,但是这样我将“丢失”对象及其属性(数字)

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM