Noooooob Noooooob - 9 months ago 44
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


<script type="text/javascript">
Person = function(fname, lname)

Person.prototype.toString = function()
return this.firstname+" "+this.lastname;

Person.prototype.keydown = function (event)
//return this.firstname+" "+this.lastname;

function init()
var k=new Person("Paul", "Nistor");

window.addEventListener("keydown", k.keydown, true);
<body onLoad="init();">
Now pressed: <input id="nowpressed" name="nowpressed" type="text" size="20" value="">

Answer Source

One way is to provide an anonymous function:

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

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

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