This question already has answers here:
How does the “this” keyword work?
                                
                                    (22个答案)
                                
                        
                5年前关闭。
            
        

以下是我的代码,当将对象方法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);

关于javascript - 添加监听器时,JavaScript失去引用,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/29115855/

10-12 07:32