1

Suppose I have an object X defined as

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

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


In Mozilla, I can do exactly what I want with __proto__:

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

However, that is (1) nonstandard and (2) deprecated. MDN's page for __proto__ suggests using Object.getPrototypeOf instead, but what I'm really looking for is an Object.setPrototypeOf (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!).

Snowball
  • 11,102
  • 3
  • 34
  • 51
  • 1
    I believe what you're looking for is what is usually called "callable objects". You may want to do a quick search on StackOverflow for that term if it's what you're looking for. Not sure if you're going to find a solution as simple as `__proto__` offers. –  Jun 12 '12 at 19:09
  • I'm gonna go with "Why?" and "Probably not." on this one. – Ryan Kinal Jun 12 '12 at 19:13
  • @RyanKinal: A use case is shown in the bug report I linked. – Snowball Jun 12 '12 at 22:23

1 Answers1

4

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.

Community
  • 1
  • 1
Bergi
  • 630,263
  • 148
  • 957
  • 1,375
  • Why would you want that? And you still can extend Function.prototype. – Bergi Jun 12 '12 at 23:00
  • While I personally don't have a use case (I was just curious if JavaScript could do that), there is one use case in the bug report I linked in the question. – Snowball Jun 13 '12 at 01:36