在原型对象中调用函数 [英] Calling function within prototype object

查看:49
本文介绍了在原型对象中调用函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何从Set()调用PrintIt foo?我得到它无法找到的错误...

我知道可以通过MyObject.prototype.PrintIt调用它但这样我将丢失对象及其属性(Num)

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


推荐答案

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

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

这篇关于在原型对象中调用函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆