Noooooob Noooooob - 1 month ago 6
Javascript Question

JavaScript losing reference when adding an listener

Below is my code and I'm losing reference to the object when adding the objects method keydown to an eventlistener anyone know why this is happening? and whats the right way to do it

<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>

Answer

One way is to provide an anonymous function:

window.addEventListener("keydown", function() {
    k.keydown();
}, true);

Another is to bind k.keydown method to proper context explicitly:

window.addEventListener("keydown", k.keydown.bind(k), true);