Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript: using inheritance "as is"

I want to use some very simple inheritance in Javascript without any libraries (jQuery, Prototype, etc.) and I'm forgetting how to do this.

I know how to create a simple non-inherited object:

function Foo(x)
{
    this.x = x;
}
Foo.prototype = {
    inc: function() { return this.x++; }
}

which I can then use as follows:

js>f1=new Foo(0)
[object Object]
js>f1.inc()
0
js>f1.inc()
1
js>f1.inc()
2

But how would I add a subclass with one additional method that inherits the Foo "inc" method, without changing the Foo class?

function Bar(x)
{
    this.x = x;
}
Bar.prototype = new Foo();
Bar.prototype.pow = function(y) { return this.x+"^"+y+"="+Math.pow(this.x,y); }

That seems right except for this weirdness with the constructor; I have to call the Foo constructor once to create the Bar prototype, and when Bar's constructor is called, it seems like there's no way to call the Foo constructor.

Any suggestions?

like image 813
Jason S Avatar asked Jun 10 '26 02:06

Jason S


1 Answers

The trick is to use Object.create instead of doing new Foo(). It will also create a new object inheriting from Foo.prototype but without calling the Foo constructor.

Bar.prototype = Object.create(Foo.prototype);

While Object.create might not be defined on older browsers, it is possible to define it yourself if you need to. (the following code is from the MDN link)

if (!Object.create) {  
    Object.create = function (o) {  
        if (arguments.length > 1) {  
            throw new Error('Object.create implementation only accepts the first parameter.');
            //tbh, the second parameter is for stuff you dont need right now.
        }  
        function F() {}  
        F.prototype = o;  
        return new F();  
    };  
}  
like image 173
hugomg Avatar answered Jun 13 '26 07:06

hugomg



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!