Search code examples
javascriptprototype-programming

Why can't invoke the function defined in prototype of a function?


I've some javascript code:

wzq.CategoryTree = function(config) {
};
wzq.CategoryTree.prototype.hello = function() {
    alert("Hello");
};

var categoryTree = new wzq.CategoryTree({});
categoryTree.hello();

I think it should alert a "Hello" message box, but nothing happened. Where is wrong?


UPDATE

Sorry, guys, I missed something important from the working code, the CategoryTree should be:

wzq.CategoryTree = function(config) {
     return new Ext.tree.TreePanel();
};

So:

var categoryTree = new wzq.CategoryTree({});

It's actually a Ext.tree.TreePanel not a CategoryTree, that's why no hello can be found.


Solution

  • Is wzq defined? Running your code yields an Uncaught ReferenceError: wzq is not defined.

    This works: (jsfiddle)

    wzq = {};
    
    wzq.CategoryTree = function(config) {
    };
    wzq.CategoryTree.prototype.hello = function() {
        alert("Hello");
    };
    
    var categoryTree = new wzq.CategoryTree({});
    categoryTree.hello();