Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I have two module with very similar methods (it is a part of an adapter pattern that implements the same methods/interface). The differences are in two lines of code:

function MyModuleA{

}

ModuleA.prototype.myMethod = function{
           --LineA--
           --LineB--
           --LineC--
           --LineD--
}

function MyModuleB{

}

ModuleB.prototype.myMethod = function{
           --LineA--
           **--LineE--**     //different line
           --LineB--
           --LineC--
           **--LineF--**     //different line
           --LineD--
}

Can I use javascript inheritance to implement the similar lines only once?

Thanks!!

share|improve this question
    
It might depend on what the lines of code are, but generally yes. WHy don't you try it? –  Giscard Biamby Sep 21 '12 at 21:12
    
I have a problem because the similar and different lines are mixed... Hoe can I call a base class in this case? –  Yaniv Sep 21 '12 at 21:14
1  
Put the consecutive lines of shared code into different functions. Then call the functions you need in the base classes. You may not want to do this because grouping the code based on this minute similarity might not be worth it, but that's not what you were asking. –  Giscard Biamby Sep 21 '12 at 21:17
    
Indeed, I was looking for a better solution, if exists... –  Yaniv Sep 21 '12 at 21:19
1  
Anything i can think of that would do this with inheritance would be pretty clunky. Either split the code into functions as mentioned above, or use if statements around the dissimilar code to only run it under the ModuleB. –  Giscard Biamby Sep 21 '12 at 21:23

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Browse other questions tagged or ask your own question.