2

I'm using Spine.js from plain Javascript (no Coffescript).
I'm using the syntax described in the documentation to call a parent class method.

Specifically:  this.constructor.__super__.someFunction.apply(this, arguments) 

This works fine for a direct child class calling it's immediate parent class. But add a grand-child class and all hell breaks loose. Calling the method on an instance of the grand-child class results in an infinite loop. I have a jsFiddle that demonstrates this by implementing the class hierarchy shown here:

MyObjClass (implements method sayHi())
^
|
My2ndObjClass (method sayHi() calls superclass)
^
|
My3rdObjClass 

When sayHi() is called on an instance of My3rdObjClass you get an infinite loop (the Chrome console reports max stack error).

My guess is that when sayHi() runs on My3rdObj it naturally runs the parent class implementation (so, My2ndObjClass's sayHi() executes). My2ndObjClass's sayHi() then resolves super to be My2ndObjClass rather than MyObjClass (as I expected), so the call to super now becomes a recursive call, and away we go... a StackOverflow ;)

So, am I doing something wrong, or is this a limitation of Spine? I suspect there's some clever way to get around this, but I haven't found it via Google or by RTFM.

vulcan
  • 706
  • 5
  • 8

1 Answers1

0

2 things: "this" isn't what you think it is. The scoping of "this" does not follow traditional language constructs, so you need to reference the specific variable in the closure you want. In this case "my2ndObjClass".

Second, since you're using "include", your methods are defined on the instance, not the class. In the coffeescript/javascript uses of prototypes/objects, it's whether the thing you're looking for is in the constructor, object itself. So don't look in the constructor' super, just in the object's directly.

So, your definition

  my2ndObjClass.include({
    sayHi: function() {
        this.constructor.__super__.sayHi.apply(this,arguments);
    }
  });

becomes

my2ndObjClass.include({
    sayHi: function() {
        my2ndObjClass.__super__.sayHi.apply(this,arguments);
    }
  });

And it works.

IMHO, these are all the reasons to to use coffeescript, to avoid all this brittleness and convention

deafgreatdane
  • 1,211
  • 11
  • 12
  • Thanks very much! I also received this similar answer (to not use 'this') from Alex MacCaw on the Spine Google group: "For super, you should be doing: MyParentClass.prototype.someFunction.apply(this, arguments)" – vulcan Jun 14 '12 at 14:17