Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get to my ancestor’s overridden method using Crockfords's Object.create() (Javascript)

Tags:

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();
like image 654
Jan Avatar asked Nov 01 '09 13:11

Jan


2 Answers

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.

like image 150
Ferdinand Beyer Avatar answered Oct 12 '22 21:10

Ferdinand Beyer


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?

like image 44
dan_nl Avatar answered Oct 12 '22 21:10

dan_nl