gpt4 book ai didi

javascript - 如果构造函数返回 new Func() 会发生什么

转载 作者:行者123 更新时间:2023-12-02 15:34:03 26 4
gpt4 key购买 nike

当我写作时

function abc() {
return 3;
}

var t = new abc();
console.log(t); // abc {}

但是当我这样做时

function a() {
this.name = 'test';
}

function b() {
this.age = 33;
return new a();
}

var p = new b();
console.log(p); // a { name = 'test'}

那么在第一个示例中,为什么 return 实际上返回一个数字时它返回一个对象。当我返回 new Func() ....我得到新的 Obj ..返回值。

在一种情况下,我得到返回值,在另一种情况下,我得到主对象。

最佳答案

根据 ES5.1 规范 13.2.2 [[Construct]]

相关部分:

  1. Let result be the result of calling the [[Call]] internal property of F, providing obj as the this value and providing the argument list passed into [[Construct]] as args.
  2. If Type(result) is Object then return result.
  3. Return obj.

ES2015中的相似部分:9.2.2 [[Construct]] ( argumentsList, newTarget)

  1. Let result be OrdinaryCallEvaluateBody(F, argumentsList).
  2. Remove from the execution context stack and restore callerContext as the running execution context.
  3. If result.[[type]] is return, then
    • If Type(result.[[value]]) is Object, return NormalCompletion(result.[[value]]).
    • If kind is "base", return NormalCompletion(thisArgument).
    • If result.[[value]] is not undefined, throw a TypeError exception.

感谢@Barmar摘要:

In other words, if the constructor returns an object, new returns that object, otherwise it returns this

关于javascript - 如果构造函数返回 new Func() 会发生什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33092384/

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