Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can a JavaScript object have a prototype chain, but also be a function?

Tags:

function a () {
    return "foo";
}

a.b = function () {
    return "bar";
}

function c () { };
c.prototype = a;

var d = new c();
d.b(); // returns "bar"
d(); // throws exception, d is not a function

Is there some way for d to be a function, and yet still inherit properties from a?

like image 743
Daniel Cassidy Avatar asked Dec 04 '08 12:12

Daniel Cassidy


1 Answers

Actually, it turns out that this is possible, albeit in a non-standard way.

Mozilla, Webkit, Blink/V8, Rhino and ActionScript provide a non-standard __proto__ property, which allow changing the prototype of an object after it has been created. On these platforms, the following code is possible:

function a () {
    return "foo";
}

a.b = function () {
    return "bar";
}

function c () {
    return "hatstand";
}
c.__proto__ = a;

c(); // returns "hatstand"
c.b(); // returns "bar"; inherited from a

This might be of use to anyone who doesn't need to worry about cross-platform compatibility.

However, note that only the properties of an object can be inherited. For example:

var d = {};
d.__proto__ = a;
d.b(); // returns "bar"
d(); // throws exception -- the fact that d is inheriting from a function
     // doesn't make d itself a function.
like image 160
Daniel Cassidy Avatar answered Nov 16 '22 17:11

Daniel Cassidy