Define a function with a prototype chain

Suppose I have an object X defined as

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

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




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

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

However, this is (1) non-standard and (2) outdated. The MDN page for __proto__ suggests using Object.getPrototypeOf instead, but what I'm really looking for is Object.setPrototypeOf (which does not exist, although the idea is brought up in this error report ).

Cheap approximation to what I want

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

Unfortunately, this does not make f instanceof X true (and I will not expect this!).

+1
javascript
Jun 12 '12 at 19:05
source share
1 answer

No, this is not possible (in a standard way). Each possibility of creating a called object (i.e. Functions) will create one inheriting from Function.prototype 1 ; and you cannot change the [[prototype]] object after 2 .

See also:

  • create function in javascript with custom prototype
  • Can you create functions with custom prototypes in JavaScript?
  • Is it possible to create a function with a different prototype than Function.prototype?
  • Can a JavaScript object have a prototype chain and also be a function?
  • Custom prototype chain for function
  • The correct prototype chain for the function (for some internal components)

1: OK, ES6 allows us to subclass Function . But this is not as useful as it seems. 2: With ES6 you can use Object.setPrototypeOf .

+4
Jun 12 '12 at 19:19
source share



All Articles