views:

121

answers:

2
if (typeof Object.create !== 'function') {
    Object.create = function (o) {
        function F() {}
        F.prototype = o;
        return new F();
    };
}
var o1 = {};
o1.init = function(){
   alert('o1');
};
var o2 = Object.create(o1);
o2.init = function(){
   // how would I call my ancessors init()?
   alert('o2');
};
o2.init();
+3  A: 

JavaScript functions are objects and have two useful methods to invoke the function:

Function.call(scope, [arg1, ...])
Function.apply(scope, args)

You can use one of these to call the parent implementation, explicitely passing this as the scope parameter, so that in the parent implementation, this refers to the child object:

var o1 = {
    name : "One",
    init : function() {
        alert("o1: " + this.name);
    }
};

var o2 = Object.create(o1);
o2.name = "Two";
o2.init = function() {
    o1.init.call(this);
    alert("o2: " + this name);
};

This will alert: o1: Two and o2: Two.

Ferdinand Beyer
I don't think this is entering into the spirit of the question, how would o2 be aware of the existance of the o1 variable. For any such attempt at object oriented development in Javascript to make sense you can't be having this sort of coupling.
AnthonyWJones
Of course you can. If you want to call your prototype's method implementation, you have to know your prototype. This is similar to class inheritance in C++, where you have to know your parent class in order to call a overridden method (`ParentClass::method()`).
Ferdinand Beyer
+1  A: 

Maybe this is oversimplifying what you’re trying to accomplish ... would placing o1.init() in the o2 init function work?

o2.init = function(){
   // how would I call my ancessors init()?
   alert('o2');
   o1.init();
};

Out of curiosity, was "ancessors" a spelling error for "ancestor’s" or does "ancessors" mean something specific here? Did you mean o2’s "parent" object?

dan_nl