hay / stapes

the Javascript MVC microframework that does just enough
http://hay.github.io/stapes
MIT License
443 stars 54 forks source link

Inheritance with Stapes.js #37

Closed sylouuu closed 11 years ago

sylouuu commented 11 years ago

Hi!

I'm trying to make a parent/child link with Stapes.js.

Here is my code:

var Parent = Stapes.subclass({
    constructor: function () {
        this.name = 'syl';
    }
});

var Child = Parent.subclass({
    constructor: function (value) {
        this.value = value;

        console.log(this.name); // undefined
    }
});

var child = new Child('a value');

How to access to the parent's name property from the child class? fiddle here.

Any ideas guys?

Thanks, regards.

hay commented 11 years ago

Hi sylouuu, child classes do not automatically run the constructor of their parent. You need to run it manually. You could either do this:

var Child = Parent.subclass({
    constructor : function() {
        Parent.prototype.constructor.apply(this, arguments);
    }
});

or this:

var Child = Parent.subclass({
    constructor : function() {
        Child.parent.constructor.apply(this, arguments);
    } 
});

In both cases, doing a

var child = new Child();
alert(child.name);

Will give an alertbox with 'syl'

ghost commented 11 years ago
  1. A cleaner way to write the above is:
var Child = Parent.subclass({
    constructor : function() {
        Parent.apply(this, arguments);
    }
});
  1. You can change this strange behaviour, and refrain from redundent constructors like these, by adding this "plugin":
// use parent constructor by default
    var createSubclass = _.createSubclass;
    _.createSubclass = function(props, events) {
        if (!props.hasOwnProperty('constructor'))
            props.constructor = function() {
                props.superclass.apply(this, arguments)
            };
        return createSubclass.call(this, props, events);
    };