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();

- 15,848
- 18
- 99
- 158

- 6,532
- 9
- 37
- 48
3 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
.

- 64,979
- 15
- 154
- 145
-
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 Nov 01 '09 at 21:17
-
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 Nov 02 '09 at 08:52
-
What I don't like about this is that you are adding properties to o2 after its creation. When using new, you get to define the constructor functions of both parent and child before creating instances. How could you accomplish the same with Object.create? – JohnMerlino Sep 01 '14 at 05:33
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?

- 4,456
- 1
- 15
- 7
In browsers that support it, you could use the Object.getPrototypeOf
function, like this:
o2.init = function(){
Object.getPrototypeOf(this).init.call(this);
alert('o2');
};
This would get the prototype of o2
(o1
) and apply its init
method to this (o2
), just like a super.init()
in other languages.
UPDATE:
The Object.getPrototypeOf
function could be implemented like this:
if ( typeof Object.getPrototypeOf !== "function" )
{
if ( typeof ({}).__proto__ === "object" )
{
Object.getPrototypeOf = function(object)
{
return object.__proto__;
};
}
else
{
Object.getPrototypeOf = function(object)
{
// May break if the constructor has been tampered with
return object.constructor.prototype;
};
}
}
Found on this link: http://ejohn.org/blog/objectgetprototypeof/

- 1,847
- 1
- 17
- 29