JavaScript的构造函数返回函数并保持继承? [英] Can JavaScript constructor return function and keep inheritance?
本文介绍了JavaScript的构造函数返回函数并保持继承?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
function F() {
return function() {
return {};
}
}
var f = new F();
f instanceof F; // returns false
据我所知,如果我想要 instanceof
工作,我需要从构造函数中返回 this
。但我想让构造函数返回一个函数,我不能分配 this
。
As far as I understand, if I want instanceof
to work, I need to return this
from the constructor. But I want the constructor to return a function, and I cannot assign to this
.
不可能或可以以某种方式完成, f = new F()
返回一个函数,然后 f instanceof F
返回true?
So, is this really impossible or can it be done somehow, for f = new F()
to return a function and still f instanceof F
to return true?
推荐答案
function F() {
var r = function() {
return {};
};
r.__proto__ = this.__proto__;
return r;
}
var f = new F();
f instanceof F;
true
f();
Object
仅适用于 __ proto __
这篇关于JavaScript的构造函数返回函数并保持继承?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文