The preferred solution
Javascript OOP is specific in context handling: if your parent works with context (this), just call the parent in the child with its context (note the new function(), which sets the context from global to the newly created object):
var parent = function() { // constructor, should be called with new
this.someFunc = function() { return "a string"; }
}
var child = new function() { // object, was already called with new
parent.call(this); // set parent context to child's, don't create new one
var someVal = this.someFunc(); // method from parent.
}
console.log(child.someFunc()); // a string
Alternative, non-standard solution, close to your approach
If you set the parent prototype instead of working with its context, you may use non-standard __proto__
member, which has access to its prototype:
var parent = function() {} // constructor to create empty object
parent.prototype.someFunc = function() { // someFunc is in parent prototype
return "a string";
}
var child = new function() {
this.__proto__ = new parent(); // set prototype to parent with its own context
var someVal = this.someFunc(); // method from parent.
}
console.log(child.someFunc()); // a string
Compared to your working example
You may also set the prototype to the constructor, not to the object using standard prototype
. Note the object is created AFTER the prototype is set, see the position of new
calls and compare it to the Felix Kling's comment to the question:
var parent = function() {}
parent.prototype.someFunc = function() {
return "a string";
}
var child = function() { // no new here
var someVal = this.someFunc();
}
child.prototype = new parent();
console.log((new child).someFunc()); // new moved here
The error explained
Function with new
creates a constructor from function in javascript. It means that the context becomes the function itself. Without the new
(and with default non-strict behavior), the context is global context, hence your error
Object [object global] has no method 'someFunc'