Click here to Skip to main content
15,891,905 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have two javascript classes (childA and childB), each inheriting from another javascript class (Parent). The parent contains a myMethod function which is overridden by the child classes. All these classes are in different files as well which are loaded on the page.

What I'm trying to do is invoke each of the derived class's myMethod. I'm trying to keep my question very brief and to the point. There are a bunch of things going on, but I'm zeroing down on what my actual question is.

My questions:
1. What I'd like to do is get a list of registered classes dynamically which inherit from Parent. I would like to invoke myMethod of each of these derived classes.
2. Would this be a bad practice from a performance perspective?

JavaScript
...
Parent.prototype.myMethod  = function(methodName)
{
}


Thanks!
Posted
Comments
Sergey Alexandrovich Kryukov 22-Dec-11 19:25pm    
Why?!
--SA

1 solution

I think you don't understand what you want. In JavaScript, there are no classes per se, you only have instances and prototypes, which are all objects. JavaScript is a prototype-based scripting language, which does support of object-oriented style, which is not the same as classical object-oriented paradigm. All JavaScript objects are nothing but associative arrays/dictionaries.

See:
http://en.wikipedia.org/wiki/JavaScript[^],
http://en.wikipedia.org/wiki/JavaScript#Prototype-based[^].

When you say "invoke myMethod of each of these derived classes, it assumes that myMethod is a static method of classic OOP, otherwise it would requires some set of instances to be passed as "this" reference in each call. In JavaScript, there are no such things. You just have some set of object, and each of them may or may not have such method.

That said, whenever you need to invoke some set of calls of some method, you simply need a set of objects (not classes!) to call it. To have such set, you need to put your objects in some container, traverse it in for… in… loop and call the method for each object. Be ready to catch exception if the call fails.

The question about good a bad practice does not really make sense as you meant something else. There is nothing wrong with calling a method in the loop; the question of performance also makes little to know sense as it's unclear what to consider as an alternative and what's the purpose of it.

—SA
 
Share this answer
 
Comments
Monjurul Habib 23-Dec-11 15:50pm    
5!
Sergey Alexandrovich Kryukov 23-Dec-11 16:27pm    
Thank you, Monjurul.
--SA

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900