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!).
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…