gpt4 book ai didi

javascript - 从对象返回函数会破坏 instanceof

转载 作者:行者123 更新时间:2023-11-30 13:20:03 27 4
gpt4 key购买 nike

这个小 gem 让我有点头疼。假设我创建了一个返回函数的对象,如下所示:

function Bar(prop) {
this.prop = prop;
var that = this;
return function() {
this.prop = that.prop;
}
}

var bar = new Bar();
console.log(bar instanceof Bar)​;

Bar() 返回一个函数,如您所见。现在,Bar() instanceof Bar 返回 false,这不是我想要的。如何检查 new Bar() 是否是 Bar 的实例?这可能吗?

最佳答案

从构造函数返回任何对象将使用该对象,而不是返回由构造函数自动生成的实例。这有点抽象,所以这里有一个例子来说明我的观点:

function Foo() {}
function Bar() {
return new Foo();
}
f = new Foo();
console.log(f instanceof Foo); //true
b = new Bar();
console.log(b instanceof Bar); //false
console.log(b instanceof Foo); //true

JavaScript 中的一切都是对象,包括函数,所以您的 foo.bar 函数返回一个函数这一事实意味着当您调用 new foo.bar()您将收到 foo.bar 返回的函数,而不是新的 foo.bar 实例。


虽然我不能 100% 确定您要做什么,但您可以检查函数是作为对象初始值设定项调用还是作为函数调用,只需使用 instanceof 在上下文中。此模式通常用于强制对象初始化:

function Foo(...arguments...) {
if (!(this instanceof Foo)) {
return new Foo(...arguments...);
}
//do stuff
}

这允许 Foo 作为一个函数被调用并且仍然返回一个新的 Foo 实例:

a = new Foo(); //a instanceof Foo
b = Foo(); //b instanceof Foo

关于javascript - 从对象返回函数会破坏 instanceof,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10537025/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com