Generally, it's not always advisable to try and emulate patterns from other languages into Javascript. Javascript uses prototypal inheritance, and not standard OO inheritance (such as what you do in Java). Yes, you can copy methods from one prototype to another, but it is not always advisable, because you're really blowing the encapsulation of the inner object out of the water. If you do want to copy methods, you can do so simply by setting one objects prototype equal to the other.
Here is one pattern for doing inheritance
// object we want to inherit from
function bar() {}
bar.prototype.original = function() {}
// object which will inherit bar
function foo() {}
// first map prototypes
foo.prototype = new bar();
// add additional methods to foo
foo.prototype.somethingElse = function() {}
Instead of doing new bar()
you could do Object.create(bar)
, as some of the commenters have pointed out, but that is not supported in IE8 and below. The only functional difference between the two is that new bar() will execute the constructor of bar
, while the latter will not, which may or may not matter to you. Object.create()
is technically the more correct way to go, but can be a deal breaker unless you are willing to lose IE8 or use a shim.
Here is another pattern, my preferred, using composition instead
// object we want to inherit from
function bar() {}
bar.prototype.original = function() {}
function foo() {
this.bar = new bar();
}
foo.prototype.somethingElse = function() {
// foo has a bar, but isn't a bar
this.bar.original();
}