How to add an Eventlistener to an instance methodHow do JavaScript closures work?Add table row in jQueryHow do I check if an element is hidden in jQuery?How do I remove a property from a JavaScript object?How do I redirect to another webpage?How do I include a JavaScript file in another JavaScript file?How to replace all occurrences of a string in JavaScriptHow to check whether a string contains a substring in JavaScript?How do I remove a particular element from an array in JavaScript?How do I return the response from an asynchronous call?

What's a moment that's more impactful on a reread called?

How to query contacts with no cases, opportunities etc

Do native speakers use ZVE or CPU?

A DVR algebra with weird automorphisms

Grammy Winners Grading

Where or how can I find what interfaces an out of the box Apex class implements?

When did the Roman Empire fall according to contemporaries?

Identifying Lithuanian coordinate system?

Crowbar circuit causes unexpected behavior for op amp circuit

Was the Ford Model T black because of the speed black paint dries?

Are there any intersection of Theory A and Theory B?

Why isn't there research to build a standard lunar, or Martian mobility platform?

I have a ruthless DM and I'm considering leaving the party. What are my options to minimize the negative impact to the rest of the group?

Keep milk (or milk alternative) for a day without a fridge

Why do players in the past play much longer tournaments than today's top players?

Is `curl something | sudo bash -` a reasonably safe installation method?

How can an advanced civilization forget how to manufacture its technology?

What is this welding tool I found in my attic?

How to check the quality of an audio sample?

Why is dry soil hydrophobic? Bad gardener paradox

Why does Hellboy file down his horns?

Dropping outliers based on "2.5 times the RMSE"

If a specific mass of air is polluted, will the pollution stick with it?

Stuck Apple Mail - how to reset?



How to add an Eventlistener to an instance method


How do JavaScript closures work?Add table row in jQueryHow do I check if an element is hidden in jQuery?How do I remove a property from a JavaScript object?How do I redirect to another webpage?How do I include a JavaScript file in another JavaScript file?How to replace all occurrences of a string in JavaScriptHow to check whether a string contains a substring in JavaScript?How do I remove a particular element from an array in JavaScript?How do I return the response from an asynchronous call?






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;








3















I have a class in which I want to run a function whenever an event occurs. Whenever the function calls, the function of the instance of the class does not run.



class Player 
constructor()
window.addEventListener('keypress', this.key_press);
this.keys_pressed = 0;


key_press(key_press)
if(key_press.key == "w")
console.log(key_press);
this.keys_pressed += 1;

console.log(this.keys_pressed);




Whenever this.key_press is called, it logs out NaN. It seems as though the method of the class isn't being run, but rather a copy(?). I've also tried running another instance function inside key_press() but it says that the function is undefined.



Any help is appreciated.










share|improve this question
























  • As per my view NaN is coming from this line console.log(this.keys_pressed); while your code is working fine. Check here : jsfiddle.net/manektech/g8qzs0vm/1

    – Mayank Dudakiya
    Mar 26 at 4:49

















3















I have a class in which I want to run a function whenever an event occurs. Whenever the function calls, the function of the instance of the class does not run.



class Player 
constructor()
window.addEventListener('keypress', this.key_press);
this.keys_pressed = 0;


key_press(key_press)
if(key_press.key == "w")
console.log(key_press);
this.keys_pressed += 1;

console.log(this.keys_pressed);




Whenever this.key_press is called, it logs out NaN. It seems as though the method of the class isn't being run, but rather a copy(?). I've also tried running another instance function inside key_press() but it says that the function is undefined.



Any help is appreciated.










share|improve this question
























  • As per my view NaN is coming from this line console.log(this.keys_pressed); while your code is working fine. Check here : jsfiddle.net/manektech/g8qzs0vm/1

    – Mayank Dudakiya
    Mar 26 at 4:49













3












3








3


1






I have a class in which I want to run a function whenever an event occurs. Whenever the function calls, the function of the instance of the class does not run.



class Player 
constructor()
window.addEventListener('keypress', this.key_press);
this.keys_pressed = 0;


key_press(key_press)
if(key_press.key == "w")
console.log(key_press);
this.keys_pressed += 1;

console.log(this.keys_pressed);




Whenever this.key_press is called, it logs out NaN. It seems as though the method of the class isn't being run, but rather a copy(?). I've also tried running another instance function inside key_press() but it says that the function is undefined.



Any help is appreciated.










share|improve this question
















I have a class in which I want to run a function whenever an event occurs. Whenever the function calls, the function of the instance of the class does not run.



class Player 
constructor()
window.addEventListener('keypress', this.key_press);
this.keys_pressed = 0;


key_press(key_press)
if(key_press.key == "w")
console.log(key_press);
this.keys_pressed += 1;

console.log(this.keys_pressed);




Whenever this.key_press is called, it logs out NaN. It seems as though the method of the class isn't being run, but rather a copy(?). I've also tried running another instance function inside key_press() but it says that the function is undefined.



Any help is appreciated.







javascript canvas ecmascript-6 addeventlistener






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Mar 26 at 5:07









Amardeep Bhowmick

6,5892 gold badges12 silver badges32 bronze badges




6,5892 gold badges12 silver badges32 bronze badges










asked Mar 26 at 4:42









SealestrSealestr

235 bronze badges




235 bronze badges












  • As per my view NaN is coming from this line console.log(this.keys_pressed); while your code is working fine. Check here : jsfiddle.net/manektech/g8qzs0vm/1

    – Mayank Dudakiya
    Mar 26 at 4:49

















  • As per my view NaN is coming from this line console.log(this.keys_pressed); while your code is working fine. Check here : jsfiddle.net/manektech/g8qzs0vm/1

    – Mayank Dudakiya
    Mar 26 at 4:49
















As per my view NaN is coming from this line console.log(this.keys_pressed); while your code is working fine. Check here : jsfiddle.net/manektech/g8qzs0vm/1

– Mayank Dudakiya
Mar 26 at 4:49





As per my view NaN is coming from this line console.log(this.keys_pressed); while your code is working fine. Check here : jsfiddle.net/manektech/g8qzs0vm/1

– Mayank Dudakiya
Mar 26 at 4:49












2 Answers
2






active

oldest

votes


















2














When you are adding an event listener to the window or any element of the DOM, the this value points to that element instead of the Player instance.



So you are getting NaN as the window does not have the keys_pressed property and keys_pressed += 1 is treated as keys_pressed = undefined + 1 which is NaN.



To fix this we need to bind to the Player instance explicitly:






const input = document.querySelector("#input");
class Player
constructor()
input.addEventListener('keypress', this.key_press.bind(this));
this.keys_pressed = 0;


key_press(key_press)
if(key_press.key == "w")
this.keys_pressed += 1;

console.log(this.keys_pressed);


let p = new Player();

Type here: <input type="text" id="input">





We can also use an arrow ( => ) function which captures the this from the current context and would point to the current instance of the Player object:






const input = document.querySelector("#input");
class Player
constructor()
input.addEventListener('keypress', (event) => this.key_press(event));
this.keys_pressed = 0;


key_press(key_press)
if(key_press.key == "w")
this.keys_pressed += 1;

console.log(this.keys_pressed);


let p = new Player();

Type here: <input type="text" id="input">








share|improve this answer

























  • This works, thanks!

    – Sealestr
    Mar 26 at 4:56











  • @Sealestr Please accept this answer, if it solved your problem!

    – Amardeep Bhowmick
    Mar 26 at 5:14


















0














Here is another workaround with onkeypress and bind.






class Player 
constructor(input)
input.onkeypress = this.onkeyPress.bind(this);
this.keys_pressed = 0;

onkeyPress(event)
event.key=="w"? this.keys_pressed++:this.keys_pressed;
console.log(this.keys_pressed);
;


const input = document.querySelector("#input");
let p = new Player(input);

Type here: <input type="text" id="input">








share|improve this answer



























    Your Answer






    StackExchange.ifUsing("editor", function ()
    StackExchange.using("externalEditor", function ()
    StackExchange.using("snippets", function ()
    StackExchange.snippets.init();
    );
    );
    , "code-snippets");

    StackExchange.ready(function()
    var channelOptions =
    tags: "".split(" "),
    id: "1"
    ;
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function()
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled)
    StackExchange.using("snippets", function()
    createEditor();
    );

    else
    createEditor();

    );

    function createEditor()
    StackExchange.prepareEditor(
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader:
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    ,
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    );



    );













    draft saved

    draft discarded


















    StackExchange.ready(
    function ()
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55349982%2fhow-to-add-an-eventlistener-to-an-instance-method%23new-answer', 'question_page');

    );

    Post as a guest















    Required, but never shown

























    2 Answers
    2






    active

    oldest

    votes








    2 Answers
    2






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    2














    When you are adding an event listener to the window or any element of the DOM, the this value points to that element instead of the Player instance.



    So you are getting NaN as the window does not have the keys_pressed property and keys_pressed += 1 is treated as keys_pressed = undefined + 1 which is NaN.



    To fix this we need to bind to the Player instance explicitly:






    const input = document.querySelector("#input");
    class Player
    constructor()
    input.addEventListener('keypress', this.key_press.bind(this));
    this.keys_pressed = 0;


    key_press(key_press)
    if(key_press.key == "w")
    this.keys_pressed += 1;

    console.log(this.keys_pressed);


    let p = new Player();

    Type here: <input type="text" id="input">





    We can also use an arrow ( => ) function which captures the this from the current context and would point to the current instance of the Player object:






    const input = document.querySelector("#input");
    class Player
    constructor()
    input.addEventListener('keypress', (event) => this.key_press(event));
    this.keys_pressed = 0;


    key_press(key_press)
    if(key_press.key == "w")
    this.keys_pressed += 1;

    console.log(this.keys_pressed);


    let p = new Player();

    Type here: <input type="text" id="input">








    share|improve this answer

























    • This works, thanks!

      – Sealestr
      Mar 26 at 4:56











    • @Sealestr Please accept this answer, if it solved your problem!

      – Amardeep Bhowmick
      Mar 26 at 5:14















    2














    When you are adding an event listener to the window or any element of the DOM, the this value points to that element instead of the Player instance.



    So you are getting NaN as the window does not have the keys_pressed property and keys_pressed += 1 is treated as keys_pressed = undefined + 1 which is NaN.



    To fix this we need to bind to the Player instance explicitly:






    const input = document.querySelector("#input");
    class Player
    constructor()
    input.addEventListener('keypress', this.key_press.bind(this));
    this.keys_pressed = 0;


    key_press(key_press)
    if(key_press.key == "w")
    this.keys_pressed += 1;

    console.log(this.keys_pressed);


    let p = new Player();

    Type here: <input type="text" id="input">





    We can also use an arrow ( => ) function which captures the this from the current context and would point to the current instance of the Player object:






    const input = document.querySelector("#input");
    class Player
    constructor()
    input.addEventListener('keypress', (event) => this.key_press(event));
    this.keys_pressed = 0;


    key_press(key_press)
    if(key_press.key == "w")
    this.keys_pressed += 1;

    console.log(this.keys_pressed);


    let p = new Player();

    Type here: <input type="text" id="input">








    share|improve this answer

























    • This works, thanks!

      – Sealestr
      Mar 26 at 4:56











    • @Sealestr Please accept this answer, if it solved your problem!

      – Amardeep Bhowmick
      Mar 26 at 5:14













    2












    2








    2







    When you are adding an event listener to the window or any element of the DOM, the this value points to that element instead of the Player instance.



    So you are getting NaN as the window does not have the keys_pressed property and keys_pressed += 1 is treated as keys_pressed = undefined + 1 which is NaN.



    To fix this we need to bind to the Player instance explicitly:






    const input = document.querySelector("#input");
    class Player
    constructor()
    input.addEventListener('keypress', this.key_press.bind(this));
    this.keys_pressed = 0;


    key_press(key_press)
    if(key_press.key == "w")
    this.keys_pressed += 1;

    console.log(this.keys_pressed);


    let p = new Player();

    Type here: <input type="text" id="input">





    We can also use an arrow ( => ) function which captures the this from the current context and would point to the current instance of the Player object:






    const input = document.querySelector("#input");
    class Player
    constructor()
    input.addEventListener('keypress', (event) => this.key_press(event));
    this.keys_pressed = 0;


    key_press(key_press)
    if(key_press.key == "w")
    this.keys_pressed += 1;

    console.log(this.keys_pressed);


    let p = new Player();

    Type here: <input type="text" id="input">








    share|improve this answer















    When you are adding an event listener to the window or any element of the DOM, the this value points to that element instead of the Player instance.



    So you are getting NaN as the window does not have the keys_pressed property and keys_pressed += 1 is treated as keys_pressed = undefined + 1 which is NaN.



    To fix this we need to bind to the Player instance explicitly:






    const input = document.querySelector("#input");
    class Player
    constructor()
    input.addEventListener('keypress', this.key_press.bind(this));
    this.keys_pressed = 0;


    key_press(key_press)
    if(key_press.key == "w")
    this.keys_pressed += 1;

    console.log(this.keys_pressed);


    let p = new Player();

    Type here: <input type="text" id="input">





    We can also use an arrow ( => ) function which captures the this from the current context and would point to the current instance of the Player object:






    const input = document.querySelector("#input");
    class Player
    constructor()
    input.addEventListener('keypress', (event) => this.key_press(event));
    this.keys_pressed = 0;


    key_press(key_press)
    if(key_press.key == "w")
    this.keys_pressed += 1;

    console.log(this.keys_pressed);


    let p = new Player();

    Type here: <input type="text" id="input">








    const input = document.querySelector("#input");
    class Player
    constructor()
    input.addEventListener('keypress', this.key_press.bind(this));
    this.keys_pressed = 0;


    key_press(key_press)
    if(key_press.key == "w")
    this.keys_pressed += 1;

    console.log(this.keys_pressed);


    let p = new Player();

    Type here: <input type="text" id="input">





    const input = document.querySelector("#input");
    class Player
    constructor()
    input.addEventListener('keypress', this.key_press.bind(this));
    this.keys_pressed = 0;


    key_press(key_press)
    if(key_press.key == "w")
    this.keys_pressed += 1;

    console.log(this.keys_pressed);


    let p = new Player();

    Type here: <input type="text" id="input">





    const input = document.querySelector("#input");
    class Player
    constructor()
    input.addEventListener('keypress', (event) => this.key_press(event));
    this.keys_pressed = 0;


    key_press(key_press)
    if(key_press.key == "w")
    this.keys_pressed += 1;

    console.log(this.keys_pressed);


    let p = new Player();

    Type here: <input type="text" id="input">





    const input = document.querySelector("#input");
    class Player
    constructor()
    input.addEventListener('keypress', (event) => this.key_press(event));
    this.keys_pressed = 0;


    key_press(key_press)
    if(key_press.key == "w")
    this.keys_pressed += 1;

    console.log(this.keys_pressed);


    let p = new Player();

    Type here: <input type="text" id="input">






    share|improve this answer














    share|improve this answer



    share|improve this answer








    edited Mar 26 at 5:05

























    answered Mar 26 at 4:53









    Amardeep BhowmickAmardeep Bhowmick

    6,5892 gold badges12 silver badges32 bronze badges




    6,5892 gold badges12 silver badges32 bronze badges












    • This works, thanks!

      – Sealestr
      Mar 26 at 4:56











    • @Sealestr Please accept this answer, if it solved your problem!

      – Amardeep Bhowmick
      Mar 26 at 5:14

















    • This works, thanks!

      – Sealestr
      Mar 26 at 4:56











    • @Sealestr Please accept this answer, if it solved your problem!

      – Amardeep Bhowmick
      Mar 26 at 5:14
















    This works, thanks!

    – Sealestr
    Mar 26 at 4:56





    This works, thanks!

    – Sealestr
    Mar 26 at 4:56













    @Sealestr Please accept this answer, if it solved your problem!

    – Amardeep Bhowmick
    Mar 26 at 5:14





    @Sealestr Please accept this answer, if it solved your problem!

    – Amardeep Bhowmick
    Mar 26 at 5:14













    0














    Here is another workaround with onkeypress and bind.






    class Player 
    constructor(input)
    input.onkeypress = this.onkeyPress.bind(this);
    this.keys_pressed = 0;

    onkeyPress(event)
    event.key=="w"? this.keys_pressed++:this.keys_pressed;
    console.log(this.keys_pressed);
    ;


    const input = document.querySelector("#input");
    let p = new Player(input);

    Type here: <input type="text" id="input">








    share|improve this answer





























      0














      Here is another workaround with onkeypress and bind.






      class Player 
      constructor(input)
      input.onkeypress = this.onkeyPress.bind(this);
      this.keys_pressed = 0;

      onkeyPress(event)
      event.key=="w"? this.keys_pressed++:this.keys_pressed;
      console.log(this.keys_pressed);
      ;


      const input = document.querySelector("#input");
      let p = new Player(input);

      Type here: <input type="text" id="input">








      share|improve this answer



























        0












        0








        0







        Here is another workaround with onkeypress and bind.






        class Player 
        constructor(input)
        input.onkeypress = this.onkeyPress.bind(this);
        this.keys_pressed = 0;

        onkeyPress(event)
        event.key=="w"? this.keys_pressed++:this.keys_pressed;
        console.log(this.keys_pressed);
        ;


        const input = document.querySelector("#input");
        let p = new Player(input);

        Type here: <input type="text" id="input">








        share|improve this answer















        Here is another workaround with onkeypress and bind.






        class Player 
        constructor(input)
        input.onkeypress = this.onkeyPress.bind(this);
        this.keys_pressed = 0;

        onkeyPress(event)
        event.key=="w"? this.keys_pressed++:this.keys_pressed;
        console.log(this.keys_pressed);
        ;


        const input = document.querySelector("#input");
        let p = new Player(input);

        Type here: <input type="text" id="input">








        class Player 
        constructor(input)
        input.onkeypress = this.onkeyPress.bind(this);
        this.keys_pressed = 0;

        onkeyPress(event)
        event.key=="w"? this.keys_pressed++:this.keys_pressed;
        console.log(this.keys_pressed);
        ;


        const input = document.querySelector("#input");
        let p = new Player(input);

        Type here: <input type="text" id="input">





        class Player 
        constructor(input)
        input.onkeypress = this.onkeyPress.bind(this);
        this.keys_pressed = 0;

        onkeyPress(event)
        event.key=="w"? this.keys_pressed++:this.keys_pressed;
        console.log(this.keys_pressed);
        ;


        const input = document.querySelector("#input");
        let p = new Player(input);

        Type here: <input type="text" id="input">






        share|improve this answer














        share|improve this answer



        share|improve this answer








        edited Mar 26 at 6:07

























        answered Mar 26 at 6:01









        Mawia HLMawia HL

        2,6091 gold badge16 silver badges41 bronze badges




        2,6091 gold badge16 silver badges41 bronze badges



























            draft saved

            draft discarded
















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid


            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.

            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function ()
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55349982%2fhow-to-add-an-eventlistener-to-an-instance-method%23new-answer', 'question_page');

            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            Kamusi Yaliyomo Aina za kamusi | Muundo wa kamusi | Faida za kamusi | Dhima ya picha katika kamusi | Marejeo | Tazama pia | Viungo vya nje | UrambazajiKuhusu kamusiGo-SwahiliWiki-KamusiKamusi ya Kiswahili na Kiingerezakuihariri na kuongeza habari

            Swift 4 - func physicsWorld not invoked on collision? The Next CEO of Stack OverflowHow to call Objective-C code from Swift#ifdef replacement in the Swift language@selector() in Swift?#pragma mark in Swift?Swift for loop: for index, element in array?dispatch_after - GCD in Swift?Swift Beta performance: sorting arraysSplit a String into an array in Swift?The use of Swift 3 @objc inference in Swift 4 mode is deprecated?How to optimize UITableViewCell, because my UITableView lags

            Access current req object everywhere in Node.js ExpressWhy are global variables considered bad practice? (node.js)Using req & res across functionsHow do I get the path to the current script with Node.js?What is Node.js' Connect, Express and “middleware”?Node.js w/ express error handling in callbackHow to access the GET parameters after “?” in Express?Modify Node.js req object parametersAccess “app” variable inside of ExpressJS/ConnectJS middleware?Node.js Express app - request objectAngular Http Module considered middleware?Session variables in ExpressJSAdd properties to the req object in expressjs with Typescript