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();
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
.
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?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With