问题描述
我有一个javascript文件,其中的类包含方法功能.我想知道如何从onClick事件中调用类实例方法.
I have a javascript file with classes which contain method functions. I was wondering how to go about calling a class instance method from an onClick event.
function MyClass()
{
this.instanceData = "Display Me";
this.DisplayData = function()
{
document.write(this.instanceData);
}
}
var classInstance = new MyClass();
如何通过onClick事件在classInstance上调用DisplayData函数.例如:
How would I call the DisplayData function on classInstance from an onClick event. For example:
<button onClick="classInstance.DisplayData()">Click Me!</button>
这行不通,但是可以帮助我弄清楚我要做什么.有什么建议吗?
Which doesn't work, but helps me clarify what I'm looking to do. Any suggestions?
推荐答案
您注意到,这是行不通的,因为您声明的var仍在执行块的范围内.如果删除var,它将起作用,因为 classInstance
现在位于全局范围内.
As you notice, this does not work, because the var you've declared, stays in the scope of the executing block. If you remove the var, it'll work, because classInstance
is now in the global scope.
function MyClass() {
this.instanceData = "Display Me";
this.DisplayData = function() {
alert(this.instanceData);
}
}
classInstance = new MyClass();
并这样称呼它:
<button onClick="classInstance.DisplayData.call(classInstance)">Click Me!</button>
这篇关于调用类实例方法onclick javascript的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!