tags:

views:

60

answers:

1

Consider the JavaScript code below, inspired from the YUI documentation on YAHOO.lang.extend.

In this code Class1 has a "static method" named factory() (say because it is a kind of object factory). Class2 inherits from Class1 using YAHOO.lang.extend. Why wouldn't factory() be automatically defined in Class2? Is this a reasonable expectation, or is there a better way to do this?

YAHOO.namespace("test");

YAHOO.test.Class1 = function() {};
YAHOO.test.Class1.factory = function() { console.log("Class1 static"); }
YAHOO.test.Class1.prototype.testMethod = function(info) { console.log("Class1: " + info); };

YAHOO.test.Class2 = function(info) { YAHOO.test.Class2.superclass.constructor.call(this, info); };
YAHOO.lang.extend(YAHOO.test.Class2, YAHOO.test.Class1);
YAHOO.test.Class2.prototype.testMethod = function(info) { console.log("Class2: " + info); };

YAHOO.test.Class1.factory(); // Works fine
YAHOO.test.Class2.factory(); // "Static method" is not inherite
+1  A: 

From the docstring of the method:

Utility to set up the prototype, constructor and superclass properties to support an inheritance strategy that can chain constructors and methods. Static members will not be inherited.

Emphasis mine.

When you use the extend() method as in your example, the inheritance chain will look like:

                superclass                constructor
    +-------------------------------+    ----------------> class2()
    |                               |  /            
    |          +---------+          | /        +---------+
    v    proto |         |          |/   proto |         |
   { } <-------|  class1 |         { } <-------|  class2 |
    |          |         |          |          |         |
    |          +---------+          |          +---------+
    v              |                v           
testMethod()       |            testMethod()      
                   v                            
               factory()

If you wanted factory() to be accessible from class2, you'd have to stick it on class1.prototype.

Karl Guertin
Karl, I missed that "Static members will not be inherited" at the end of that sentence. I guess the YUI guys decided against copying "static methods", and I still wonder why they did decide not to.
Alessandro Vernet