Call this._super () from inside setTimeout ()

We are using inherit.js from John Resig. And this gives us access to the convenient _super() function to call the parent function. This is awesome, but today I was shocked by the problem, I could not call this._super() from inside setTimeout , even if I linked this:

Code example

 var Person = Class.extend({ init: function(isDancing){ this.dancing = isDancing; }, dance: function(){ return this.dancing; } }); var Ninja = Person.extend({ init: function(){ this._super( false ); }, dance: function(){ window.setTimeout(function(){ // Call the inherited version of dance() return this._super(); }.bind(this),50); }); 

this._super() undefined! What's happening?

+4
source share
2 answers

To do this, you need to capture the _super method during the subclass, for example:

 dance: function(){ // capture the super method for later usage var superMethod = this._super; window.setTimeout(function(){ return superMethod(); },50); }; 

The reason this works and your code does not work is because the extend() method in inherit.js captures the superclass' method like this._super before running your overridden method. Then it runs your code, and after your code runs it, restores _super to what was installed before it was run. The action takes place in the next bit of code from inherit.js

  var tmp = this._super; // Add a new ._super() method that is the same method // but on the super-class this._super = _super[name]; // The method only need to be bound temporarily, so we // remove it when we're done executing var ret = fn.apply(this, arguments); this._super = tmp; return ret; 

To be more specific; when the source code was run, the function that was used as the parameter for setTimeout was bound to the source object. The reason it didn’t work was because although this referring to the right object, this._super referring to something else since this._super was reset to indicate what it was pointing to launch method. It probably wasn't installed, so the value of this._super was most likely undefined .

+4
source

This shows how the ugly Class is executed. The _super property will be available only during dance execution and will be deleted (or restored) after that, since it must be specific to the current executable method. You will need to get a link to the current _super value and call it from the timeout. In short:

 dance: function(){ // Call the inherited version of dance() window.setTimeout( this._super.bind(this), 50); } 
+2
source

All Articles