【发布时间】:2020-06-30 23:11:20
【问题描述】:
如何直接从return 语句中返回使用new 运算符调用的JS 函数的值?代码示例:
function Sum() {
this.one = 1;
this.two = 2;
return this.one + this.two;
}
const mySum = new Sum();
【问题讨论】:
标签: javascript oop object
如何直接从return 语句中返回使用new 运算符调用的JS 函数的值?代码示例:
function Sum() {
this.one = 1;
this.two = 2;
return this.one + this.two;
}
const mySum = new Sum();
【问题讨论】:
标签: javascript oop object
在您的示例中,您可以这样做:
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 运算符的函数。
【讨论】:
默认情况下,当我们使用new 运算符时,JS 会创建一个对象作为输出,请参阅注释。即使我们尝试返回一个原始值,我们也会使用对象反射函数的this 来代替。 JS 不允许返回 string、number 等原始值。
注意:这里默认表示如果我们不提供返回或尝试返回原始值
解决方法是返回数组、对象或函数,如下所示:
数组
function Sum() {
this.one = 1;
this.two = 2;
return [this.one + this.two];
}
const mySum = new Sum();
console.log(mySum) // [3]
对象
function Sum() {
this.one = 1;
this.two = 2;
return { result: this.one + this.two };
}
const mySum = new Sum();
console.log(mySum) // { result: 3 }
功能
function Sum() {
this.one = 1;
this.two = 2;
return () => this.one + this.two;
}
const mySum = new Sum();
console.log(mySum()) // 3
【讨论】:
“new”操作符会为您新建的任何内容创建一个实例。换句话说,它将返回事物的新副本。
换一种说法:new 操作符将导致事物的一个实例被返回。您创建的每个新实例都将拥有自己的、唯一的、单独的、个人的“this”——而“this”就是不同实例如何/为什么可以为每个属性包含不同值的方式。
如果您希望从创建的实例中获取一些价值,只需在其中包含一个附加属性:
function Sum() {
this.one = 1;
this.two = 2;
this.result = this.one + this.two;
}
...然后使用“点”加上您定义的属性来访问它。
const mySum = new Sum().result;
console.log(mySum);
...上面只是简写
const mySum = new Sum();
const value = mySum.result
console.log(value);
...但是通过使用速记方法,您失去了对实例的引用,您将永远无法恢复:(
【讨论】: