Tutorial :Javascript does not execute Object methods



Question:

I'm trying to build some objects to make my life a bit easier, but somehow I can't get it working. I got the following code:

function Paragraph(className, innerHTML, parentId) {      this.className = className;      this.innerHTML = innerHTML;      this.parentId = parentId;  }    Paragraph.generateParagraph = function() {        console.debug(this.parentId); // Expect 'testDiv'      alert(this.parentId);   // Expect 'testDiv'  };    function initialize() {      var paragraph = new Paragraph('testClass', 'testTitle', 'testDiv');      paragraph.generateParagraph;  }    window.onload = initialize;  

When I try to execute this code nothing happens. I expect the console.debug and alert in the generateParagraph method to be executed.

Any help would be appreciated!


Solution:1

Add methods to the constructor's prototype, not the constructor itself.

function Paragraph(className, innerHTML, parentId) {      this.className = className;      this.innerHTML = innerHTML;      this.parentId = parentId;  }    Paragraph.prototype.generateParagraph = function() {        console.debug(this.parentId);  // Expect 'testDiv'      alert(this.parentId);   // Expect 'testDiv'  };    function initialize() {      var paragraph = new Paragraph('testClass', 'testTitle', 'testDiv');      paragraph.generateParagraph();  }    window.onload = initialize;  


Solution:2

change

Paragraph.generateParagraph = function() {     

to

Paragraph.prototype.generateParagraph = function() {     

You added the function as a property of the constructor function, rather than to the prototype. By adding the function to the prototype it will be part of the object created when calling the constructor function using the new keyword.

Also, you need parentheses to the call to generateParagraph, otherwise you get a reference to the function, rather than calling the function:

paragraph.generateParagraph();  


Solution:3

You are not executing the generateParagraph function, as parenthesis are missing...

paragraph.generateParagraph  

This gets the function as a callback...
To call it:

paragraph.generateParagraph();  


Solution:4

you're not invoking the function.

paragraph.generateParagraph();  

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »