javascript - 使用 JavaScript 中函数的“new”运算符返回值
问题描述
如何从语句中new
直接使用运算符调用的 JS 函数返回值?return
代码示例:
function Sum() {
this.one = 1;
this.two = 2;
return this.one + this.two;
}
const mySum = new Sum();
解决方案
在您的示例中,您可以执行以下操作:
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 运算符的函数。
推荐阅读
- arduino - Octave 的 Arduino 包
- node.js - 如何在 ejs 中显示 youtube 视频
- django - 在 Admin 中创建父模型时向相关模型添加新行
- java - 如何将 int 与字符串数组进行比较?
- python - 如何在多维 numpy 数组中选择数据?
- google-cloud-platform - Gcloud - 无法使用一个服务帐户配置多个 VM
- python - Python regex:重命名所有文件,但名称中包含今天日期的文件除外
- java - 将 Apache Beam 的 PCollection 对象收集到驱动程序的内存中
- c# - 如何从 C# 中的抽象列表中访问派生类的成员变量
- matlab - 神经网络的学习曲线