Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
488 views
in Technique[技术] by (71.8m points)

javascript - 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 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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...