view raw
Snowball Snowball - 6 months ago 36
Javascript Question

Define a function with a prototype chain

Suppose I have an object

defined as

var X = function () {};
X.prototype.doSomething = function () {};
X.prototype.doSomethingElse = function () {};

Is it possible to construct a function
so that
f instanceof X
Note that I must also be able to do
without a

In Mozilla, I can do exactly what I want with

var f = function () {};
f.__proto__ = new X;

However, that is (1) nonstandard and (2) deprecated. MDN's page for
suggests using
instead, but what I'm really looking for is an
(which doesn't exist, though the idea is brought up in this bug report).

A cheap approximation to what I want is

var f = function () {};
jQuery.extend(f, new X);

Unfortunately, this does not make
f instanceof X
true (nor would I
expect it to!).


No, it is not possible (in a standard way). Every possibility to create a callable object (i.e., a function) will create one inheriting from Function.prototype1; and you can't change the [[prototype]] of an object afterwards2.

See also:

1: OK, ES6 allows us to subclass Function. But that's not as useful as it sounds.
2: Since ES6, you can use Object.setPrototypeOf.