Javascript scope addEventListener and this

后端 未结 3 2031
无人及你
无人及你 2020-12-07 23:22

I am a C# developer experimenting with JavaScript and I\'m trying to get my head around the scope :)

I have the following code which contains an addEventListe

3条回答
  •  Happy的楠姐
    2020-12-07 23:58

    Keyboard.prototype.listen = function() {
        var self = this;
        window.addEventListener('keydown', function(event) {
           self.handle_keydown(event);
           // self is your Keyboard object. You can refer to all your properties from this
        });
    }
    

    How this code works:

    1. We are creating variable self, which stores reference to this variable.
    2. The inner function is a closure, hence it has reference to self.
    3. When the closure function is called: this points to the dom object, while self points to keyboard object.
    4. The closure is called with event as a parameter that we pass on to the member function of the keyboard object.

提交回复
热议问题