当使用 new
调用构造函数时,Javascript 中的 return
语句在什么情况下可以返回 this
以外的值> 关键字?
例子:
function Foo () {
return something;
}
var foo = new Foo ();
如果我没记错的话,如果something
是一个非函数原语,this
将被返回。否则返回 something
。这是正确的吗?
换句话说,something
可以取什么值来导致 (new Foo () instanceof Foo) === false
?
最佳答案
在 [[Construct]]
中描述了确切的条件 new
使用的内部属性运算符(operator):
来自 ECMA-262 3rd。版本说明:
13.2.2
[[Construct]]
When the
[[Construct]]
property for aFunction
objectF
is called, the following steps are taken:
- Create a new native ECMAScript object.
- Set the
[[Class]]
property ofResult(1)
to"Object"
.- Get the value of the prototype property of
F
.- If
Result(3)
is an object, set the[[Prototype]]
property ofResult(1)
toResult(3)
.- If
Result(3)
is not an object, set the[[Prototype]]
property ofResult(1)
to the originalObject
prototype object as described in 15.2.3.1.- Invoke the
[[Call]]
property ofF
, providingResult(1)
as thethis
value and providing the argument list passed into[[Construct]]
as the argument values.- If
<a href="http://bclary.com/2004/11/07/#a-8" rel="noreferrer noopener nofollow">Type</a>(Result(6))
isObject
then returnResult(6)
.- Return
Result(1)
.
看第7步和第8步,只有当
Result(6)
的类型(从 F
构造函数返回的值
函数)不是对象。
关于javascript - 构造函数可以返回什么值来避免返回 this?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1978049/