How can I return values from JS function invoked with the new operator directly from return statement? Example of the code:
function Sum() {
this.one = 1;
this.two = 2;
return this.one + this.two;
}
const mySum = new Sum();
In your example you could do:
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
However, it really begs the question why you'd want to do this instead of just using a function without the new operator.
By default JS creates an object as an output when we use new operator, see note. Even if we try to return a primitive value, we have object reflected functions's this instead. JS does not allow to return a primitive value such as string, number, etc.
Note: Here by default means if we don't provide return or try to return a primitive value
The work around is to return either array, object or function like this:
Array
function Sum() {
this.one = 1;
this.two = 2;
return [this.one + this.two];
}
const mySum = new Sum();
console.log(mySum) // [3]
Object
function Sum() {
this.one = 1;
this.two = 2;
return { result: this.one + this.two };
}
const mySum = new Sum();
console.log(mySum) // { result: 3 }
Function
function Sum() {
this.one = 1;
this.two = 2;
return () => this.one + this.two;
}
const mySum = new Sum();
console.log(mySum()) // 3
The "new" operator creates an instance of whatever you're new'ing. In other words, it will return a fresh copy of the thing.
Said yet another way: The new operator will cause an instance of the thing to be returned. Each new instance that you create will have it's own, unique, separate, personal "this" -- and the "this" is how/why different instances can contain different values for each of the properties.
If you wish to get some value out of the instance that was created, just include an additional property in there:
function Sum() {
this.one = 1;
this.two = 2;
this.result = this.one + this.two;
}
... then access it using the "dot" plus the property you've defined.
const mySum = new Sum().result;
console.log(mySum);
... above is just short-hand for
const mySum = new Sum();
const value = mySum.result
console.log(value);
... but by doing the short-hand approach, you loose your reference to the instance, which you'll never be able to recover :(