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;
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
add a comment |
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
As per my view NaN is coming from this lineconsole.log(this.keys_pressed);
while your code is working fine. Check here : jsfiddle.net/manektech/g8qzs0vm/1
– Mayank Dudakiya
Mar 26 at 4:49
add a comment |
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
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
javascript canvas ecmascript-6 addeventlistener
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 lineconsole.log(this.keys_pressed);
while your code is working fine. Check here : jsfiddle.net/manektech/g8qzs0vm/1
– Mayank Dudakiya
Mar 26 at 4:49
add a comment |
As per my view NaN is coming from this lineconsole.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
add a comment |
2 Answers
2
active
oldest
votes
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">
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
add a comment |
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">
add a comment |
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
);
);
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
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
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">
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
add a comment |
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">
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
add a comment |
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">
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">
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
add a comment |
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
add a comment |
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">
add a comment |
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">
add a comment |
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">
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">
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
add a comment |
add a comment |
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.
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
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
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
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
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