首页 > 解决方案 > 使用 JavaScript 中函数的“new”运算符返回值

问题描述

如何从语句中new直接使用运算符调用的 JS 函数返回值?return代码示例:

function Sum() {
    this.one = 1;
    this.two = 2;
    return this.one + this.two;
}

const mySum = new Sum();

标签: javascriptoopobject

解决方案


在您的示例中,您可以执行以下操作:

function Sum() {
    this.one = 1;
    this.two = 2;
    return new Number(this.one + this.two);
}

const s = new Sum();
console.log(s.valueOf()) // 3
console.log(s + 3) // 6

但是,这确实引出了一个问题,为什么您要这样做,而不是仅使用没有 new 运算符的函数。


推荐阅读