JavaScript 添加侦听器时丢失引用
JavaScript losing reference when adding an listener
下面是我的代码,当我将对象方法 keydown 添加到事件监听器时,我丢失了对对象的引用有人知道为什么会这样吗?正确的方法是什么
<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);
下面是我的代码,当我将对象方法 keydown 添加到事件监听器时,我丢失了对对象的引用有人知道为什么会这样吗?正确的方法是什么
<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);