How can I Call a JavaScript's method declared inside a class? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

How can I Call a JavaScript's method declared inside a class?

How can I call a method on an onclick event whose class looks like this: class people{ constructor(){ this.name=name; this.age=age; } greeting(){ this.name=document.getElementById('personName').value; } }....... HTML ... How will the html code will look like? So that when I clicks a button, it diplays greeting()

11th Jun 2019, 1:23 PM
Kimathi Edwin
 Kimathi Edwin - avatar
5 Answers
11th Jun 2019, 2:07 PM
Anton Böhler
Anton Böhler - avatar
+ 1
maybe something like this: html: <button onclick="greeting()">greeting</button> js: function greeting(){ var p = new People(); p.greeting(); }
11th Jun 2019, 1:53 PM
Anton Böhler
Anton Böhler - avatar
+ 1
Hi Kimathi! There are two things why it didn't worked: - "people()" misspelt in line: var p = new People(); - method greeting() doesn't returns anything. Note that usually class identifiers are PascalCased.
11th Jun 2019, 2:09 PM
777
777 - avatar
0
Does not work. I think its because greeting() is a method which is inside a class. I don't know how to go about it
11th Jun 2019, 1:58 PM
Kimathi Edwin
 Kimathi Edwin - avatar
0
Thank you. It worked
11th Jun 2019, 2:14 PM
Kimathi Edwin
 Kimathi Edwin - avatar