haroldiedema / joii

Javascript Object Inheritance Implementation
MIT License
70 stars 13 forks source link

inheritance chain works strange #9

Closed dsh2dsh closed 9 years ago

dsh2dsh commented 10 years ago

Here the code:

var A = new Class({
  test: function() {
    console.log( "A" );
  }
});

var B = new Class( { "extends": A }, {
  test: function() {
    this[ "super" ]( "test" );
    console.log( "B" );
  }
});

var C = new Class( { "extends": B }, {
});

var c = new C;
c.test()

it outputs:

A
B
B

I expect output:

A
B

Looks like JOII copies content of B.test into C.test, because C doesn't have test method. May be, instead of copying parent's content, just create into C method like this:

test: function() {
  return this[ "super" ]( "test" );
}
haroldiedema commented 10 years ago

Interesting find. I'll look into it.

haroldiedema commented 10 years ago

Changing this behavior messes up the scope the parent function is called in.

At line 419 in joii.js replace the line product.prototype[i] = parent.prototype[i]; with the following code:

    if (typeof(parent.prototype[i]) === 'function') {
        product.prototype[i] = function() {
            var fn = this.__joii__.parent.prototype[i];
            return fn.apply(this.__joii__.parent, arguments);
        };
    } else {
        product.prototype[i] = parent.prototype[i];
    }

Changing the first argument of apply to this instead of this.__joii__.parent gives different results in the unit tests, but still messes up a lot of existing things.

If you can find a better (or rather working) way of doing this, please let me know, since this is a valid issue.

The problem is that the scope of the super method is in every class. In order to solve this, the scope of super needs to be altered for methods that don't exist in the class the method is called in (e.g. the class C in your example: this.super.bind(this.__joi__.parent); )

However, in order to do this automatically in the class builder, is quite a challenge. Especially without breaking existing code.

haroldiedema commented 9 years ago

Will be fixed in JOII 3.0.