【问题标题】:Strange behaviour of Javascript `new` from `function` [duplicate]来自`function`的Javascript`new`的奇怪行为[重复]
【发布时间】:2021-01-30 13:21:13
【问题描述】:

我刚刚遇到了一件让我非常惊讶的事情。考虑以下四个函数:

function A() {
 this.q = 1;
}

function B() {
 this.q = 1;
 return this;
}

function C() {
 this.q = 1;
 return 42;
}

function D() {
 this.q = 1;
 return {};
}

让我们从所有对象中创建对象(通过new):

console.log('a', new A());
console.log('b', new B());
console.log('c', new C());
console.log('d', new D());

这是输出:

a A { q: 1 }
b B { q: 1 }
c C { q: 1 }
d {}

前三个似乎表明函数返回什么并不重要,JS 只关心每个函数对this 的作用(这是我以前相信的,顺便说一句)。但最后一个与此相矛盾。

那么,这里发生了什么?我修改后的规则是“如果函数返回Object,我们保留它。否则,我们保留this”。但我对此感到很不确定。

【问题讨论】:

标签: javascript javascript-objects


【解决方案1】:

当您使用 new 运算符时,它会创建一个对象。

返回值符合预期。如果在返回中它是一个对象将返回该对象,否则如果返回它是一个函数将返回该函数。

function A(){
    this.b = 3;
    return function(){return 4;};
}
function B(){
    this.b = 3;
    return { d:4};
}

console.log(typeof (new A())); //function
console.log(typeof (new B())); //object {d:4}

如果返回值中不存在任何其他值或不存在,this 运算符将优先作为对象返回。

function C(){
    this.b = 3;
    return "78";
}
console.log(typeof (new C())); // object {b:3}

【讨论】:

  • 我选择这个作为接受的答案,因为它还包括typeof Ffunction 而不是object 的情况。 @Lorand,请同时附上@Jaromanda X 提供的link from MDN
【解决方案2】:

在 JavaScript 中,当您调用没有 new 的函数时,例如 test(),它只会运行该函数并执行它。返回函数返回的任何内容

当您使用 new test() 之类的 new 调用函数时,它希望 return 语句返回一个对象,否则返回 this 对象。

所以

function test() {
    this.q = 1
}

test(); // return undefined

new test(); // return {q:1}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-11
    • 2015-10-24
    • 2018-09-25
    相关资源
    最近更新 更多