我看到这段代码here:
function f(){ return f; }
new f() instanceof f; //false
这是因为(从我read开始):
When the
constructorreturns an object,thenewoperator will yield
the returned object
因此,由于f是一个函数 – 新的运算符将产生返回的对象,在这种情况下为f
所以:new f()=== f
因此:f instanceof f // false.
题 :
我在文档中搜索此行为描述,但找不到它.
我在mdn只找到了部分答案:
然而 – 看着docs(这是我真正追求的):
它只是说:
它没有提到构造函数返回对象的情况(我确定我错过了它)
题:
文档在哪里解释了行为?
nb,
我知道构造函数不应该(通常)返回任何东西,这个问题是为了知识.
nb2:
此行为的示例:
var z = {a: 2};
function g() { return z; }
var x = new g();
x === z; //true
在这里,x实际上等于z,直到身份!
解决方法
[[Construct]] method的属性,而不是新的:
1. Let
objbe a newly created native ECMAScript object.
[…]
8. Letresultbe the result of calling the[[Call]]internal property ofF,providingobjas the this value and providing the argument list passed into[[Construct]]asargs.
9. IfType(result)isObjectthen returnresult.
10. Returnobj.
F是通过new调用的函数(在您的情况下为f).由于f返回一个对象(步骤8),因此返回它(步骤9).如果它不是对象,则返回步骤1中的对象(步骤10).
new只返回[[Construct]]返回的内容:
5. Return the result of calling the
[[Construct]]internal method […]