简体   繁体   中英

Number prototype

Hi everyone i need an help. I try to modify Number.prototype to add the function sum. I want to add some numbers to my initial number.

 Number.prototype.sum = async (...nums) => { var x = //What I have to write to have my inizial number here? for (var i = 0;i<nums.length;i++) { x=x+nums[i] } return x } console.log((10).sum(2)) // output: 12 console.log((10).sum(4,6)) // output: 20

(I use visual studio code and the hint after this. is only number ) I tried with:

Number.prototype.valueOf(this)

Number.prototype.valueOf(this.number)

Number.parseInt(this.toString())

Number.parseFloat(this.toString())

Number.parseInt(this.number.toString())

Number.parseFloat(this.number.toString())

this.valueOf()

this.number.valueOf()

You have to use function to access the correct this context (which is the number that the method is called on). Arrow functions inherit their this context from the parent scope (the global object in this case). Also async is not needed since you are not doing anything asynchronous here:

 Number.prototype.sum = function (...nums) { var x = this for (var i = 0; i < nums.length; i++) { x = x + nums[i] } return x } console.log((1).sum(2, 3))

Aside from the fact that augmenting native prototypes is a bad idea, wouldn't you think that a function like this is better suited for the Array prototype?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM