当我尝试调用“测试”函数时出现错误。
如何解决? (没有 jquery!)
浏览器:火狐
错误:
TypeError: this.Test is not a function
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<title>Untitled Document</title>
<script type="text/javascript">
MyClass = function(){
}
MyClass.prototype = {
Init: function(){
var txt = document.getElementById("text");
if (txt.addEventListener) {
txt.addEventListener("keyup", this.Foo, true)
}
},
Foo: function(){
this.Test();
},
Test: function(){
alert('OK');
}
}
window.onload = function(){
obj = new MyClass;
obj.Init();
}
</script>
</head>
<body>
<textarea id="text" rows="10">
</textarea>
</div>
</body>
最佳答案
这是因为您将 this.Foo
引用为事件,实际发生的是它将该函数复制到对象范围之外,因此 this
不存在。大多数人所做的是在事件周围使用匿名函数/包装器。
关于javascript - 原型(prototype)内部的事件触发,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2980567/