0

Hello I have a function

Fortune.prototype.entername = function () {
    var person = prompt("Please enter your name", "Harry Potter");
    if (person != null) {
        document.getElementById("demo").innerHTML =
        "Hello " + person + "! Check Your Fortune";
    };
    this.words();
} 

I want to call it using button here is my code <p class="dark" id="demo"><button onclick="this.entername()">Click to Enter Name & see your Fortune</button></p>

However it says this.entername() is not a function. Silly mistake I dont know how to call it full js code is here https://jsfiddle.net/e9zywrnt/

  • What do you think `this` is in the scope of an event handler attribute? – Bergi Apr 09 '18 at 19:15
  • @Bergi I get error this.entername is not a function. I dont really know because in this case I am using .prototype in function. Before I just used to enter function name – Aryan Chaurasia Apr 09 '18 at 19:17
  • What do you mean by before? It is really unclear how you expect an event handler on a DOM element to access your `Fortune` instance. – Bergi Apr 09 '18 at 19:23
  • @Bergi I just want the Fortune.prototype.entername fnction to run when button is clicked – Aryan Chaurasia Apr 09 '18 at 19:27
  • Possible duplicate of [JavaScript: bind an object's method to event handler](https://stackoverflow.com/questions/20586072/javascript-bind-an-objects-method-to-event-handler) – Heretic Monkey Apr 09 '18 at 19:29
  • Then use `onclick="Fortune.prototype.entername()"`. But why are you trying to make that a method at all? What should the `this` instance inside it represent, what should `this.words()` do? – Bergi Apr 09 '18 at 19:29
  • @Bergi It runs now this.words() is another function which also is triggered. – Aryan Chaurasia Apr 09 '18 at 19:33
  • Still you should not use prototype methods at all if you don't have multiple objects that would use them. Your previous code with a plain function was just fine. – Bergi Apr 09 '18 at 19:54

0 Answers0