Subj : Re: Calling base class static method using derived class To : netscape.public.mozilla.jseng From : Peter Wilson Date : Thu Aug 25 2005 11:35 pm rush@manbert.com wrote: > Hello, > > In C++, I can do this (ignoring constructors, etc.): > > class Base > { > public: > static int baseMethod (void); > }; > > class Derived : public Base > { > }; > > > Base::baseMethod (); > Derived::baseMethod (); > > i.e. I can use the derived class type to call the base class static > method. Should I be able to do this in javascript/SpiderMonkey? > > I did the equivalent to this, then wrote this JS code: > var b = new Base (); > b.baseMethod(); > Base.baseMethod(); > > var d = new Derived (); > d.baseMethod(); > Derived.baseMethod(); > > The JS engine threw an exception at the last line > (Derived.baseMethod()). > > I'm trying to figure out whether this is correct behavior or not. If I > should be able to make this call (assuming it should work like C++), > then what is required to make it possible? (Of course, maybe this is a > gcc extension to standard C++. Maybe I should try it on a Windows > machine...sigh...) > > Thanks, > Rush > You can do this in JavaScript using the 'call' method on a function. So.... // Declare two classes, a and b. b derives from a: function a() { } function b() { } b.prototype = new a; // Declare method 'M' on 'a' a.prototype.M = function() { write("method 'M' on 'a' called"); } // Declare method 'M' on 'b' that does some work and calls // the method in the derived class. b.prototype.M = function() { write("method 'M' on 'b' called"); a.prototype.M.call(this); } // Create instance of 'b' var myObj = new b // Invoke 'M' on myObj: myObj.M(); // You can also call 'a's method on 'b' directly a.prototype.M.call(myObj) The 'call' method simply means invoke the requested method and use the parameter passed as 'this'. Because of the loosely typed nature of JavaScript of course you can invoke any method on any object in this way! so... function c() { } c.prototype.M = function() { } c.prototype.M.call(myObj) ; also works fine - although not necessarilty usefully! Hope that helps! Pete -- http://www.whitebeam.org http://www.yellowhawk.co.uk ----- .