1

I have to implement following code in Javascript, but cannot find equivalent of super.say() in javascript. How to do this translation ?

class Foo {
    public void say() {
      System.out.println("foo");  
    }
}


class Bar extends Foo {

    static int counter = 0;

    public void say() {
        super.say();
        counter++;
        System.out.println("bar " + counter); 
    }
}
user2864740
  • 60,010
  • 15
  • 145
  • 220
JavaDeveloper
  • 5,320
  • 16
  • 79
  • 132
  • I would probably rewrite it without a notion of "classes"; the idiomatic JavaScript approach is not necessarily the idiomatic "Java OOP" approach. – user2864740 Mar 12 '14 at 23:45

2 Answers2

4

There's an article that describes it in detail: http://joshgertzen.com/object-oriented-super-class-method-calling-with-javascript/

Basically, you need to store a reference to your base method, then call it in the "derived" (perhaps "shadowed" might be a better word here) method.

Michał Dudak
  • 4,923
  • 2
  • 21
  • 28
0

The keyword super doesn't work in Javascript as in Java because there's no notion of classes. Without a class, you can't have a descendant, and thus super is useless in that context.

You could implement something super-like, as described here.

Community
  • 1
  • 1
Chris Cashwell
  • 22,308
  • 13
  • 63
  • 94
  • 1
    This is not a fair conclusion (there is no `super` keyword is correct, but otherwise it doesn't seem tangential). Traditional "OOP" classes can be *entirely emulated* in JavaScript through prototypal inheritance; as can virtual, super, and non-virtual methods. – user2864740 Mar 12 '14 at 23:42
  • @user2864740 I didn't say you couldn't do it, I said JS doesn't have a notion of classes. You can totally implement something similar to `super` in JS, just not the way the OP is looking for. – Chris Cashwell Mar 12 '14 at 23:43
  • So, then back to the question "*How* to implement super in javascript"? – user2864740 Mar 12 '14 at 23:44
  • 1
    If one "can't have a descendant", then how does [[prototype]] work? Or how does `instanceof` work? The issue with `super` is subtly different, and is caused because JavaScript doesn't directly allow a mechanism to skip the "MRO" (and virtual members) along the [[prototype]] chain. – user2864740 Mar 12 '14 at 23:47
  • Here is a trivial counter-example to the descendant claim: `a = function () {}; b = function () {}; b.prototype = new a; (new b) instanceof a` results in true. – user2864740 Mar 12 '14 at 23:54