使用原型链定义函数 [英] Define a function with a prototype chain
问题描述
假设我有一个对象 X
定义为
Suppose I have an object X
defined as
var X = function () {};
X.prototype.doSomething = function () {};
X.prototype.doSomethingElse = function () {};
是否可以构建函数 f
以便 f instanceof X
?
请注意,我必须能够在没有 TypeError
的情况下执行 f()
。
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
.
在Mozilla中,我可以用 __ proto __
完成我想要的工作:
In Mozilla, I can do exactly what I want with __proto__
:
var f = function () {};
f.__proto__ = new X;
然而,这是(1)非标准和(2)弃用。 MDN的页面 __ proto __
建议使用 Object.getPrototypeOf
,但我真正想要的是 Object.setPrototypeOf
(虽然这个想法是在此错误报告中提出的,但不存在) )。
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).
我想要的便宜近似值
var f = function () {};
jQuery.extend(f, new X);
不幸的是,这不会使 f instanceof X
true(也不是我b $ b期望它!)。
Unfortunately, this does not make f instanceof X
true (nor would I
expect it to!).
推荐答案
不,这是不可能的(在一个标准方式)。创建可调用对象(即函数)的每种可能性都将创建一个继承自 Function.prototype
1 ;然后你不能改变一个对象的 [[prototype]]
2 。
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.prototype
1; and you can't change the [[prototype]]
of an object afterwards2.
参见:
- 创建功能在javascript中使用自定义原型
- 您是否可以使用JavaScript中的自定义原型创建函数?
- 是否可以使用除Function.prototype之外的其他原型创建函数?
- JavaScript对象是否有原型链,但也可以是一个函数?
- 功能的自定义原型链
- 更正功能原型链(部分内部)
- create function in javascript with custom prototype
- Can you create functions with custom prototypes in JavaScript?
- Is it possible to create a function with another prototype than Function.prototype?
- Can a JavaScript object have a prototype chain, but also be a function?
- Custom prototype chain for a function
- Correct prototype chain for Function (for some internals)
1:好的,ES6允许我们子类功能
。但这并不像它听起来那么有用。
2:从ES6开始,你可以使用 Object.setPrototypeOf
。
这篇关于使用原型链定义函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!