下面是我的代码,当将objects方法keydown添加到eventlistener时,我将失去对对象的引用。有人知道为什么会发生这种情况吗?正确的方法是什么
<html>
<head>
<title>Testpage</title>
<script type="text/javascript">
Person = function(fname, lname)
{
this.lastname=fname;
this.firstname=lname;
}
Person.prototype.toString = function()
{
return this.firstname+" "+this.lastname;
}
Person.prototype.keydown = function (event)
{
alert(this.firstname);
//return this.firstname+" "+this.lastname;
}
function init()
{
var k=new Person("Paul", "Nistor");
document.getElementById("nowpressed").value=k.toString();
window.addEventListener("keydown", k.keydown, true);
}
</script>
</head>
<body onLoad="init();">
<form>
Now pressed: <input id="nowpressed" name="nowpressed" type="text" size="20" value="">
</form>
</body>
</html>
一种方法是提供匿名函数:
window.addEventListener("keydown", function() {
k.keydown();
}, true);
另一种方法是显式地将k.keydown方法绑定到适当的上下文:
window.addEventListener("keydown", k.keydown.bind(k), true);