Javascript does not execute Object methods
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 Par开发者_运维知识库agraph('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!
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;
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();
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();
you're not invoking the function.
paragraph.generateParagraph();
精彩评论