简体   繁体   中英

How to add object of methods into Array Object to use along the project

i want to do something like this

 class lapla {
     constructor(array){
        this.array = 
     }
     sum = () => this.array.reduce((p , c) => p + c , 0) //this function sum up all of the array items
 }

 Array.prototype.awesome = new lapla( /* i want to add here the array context*/ this)

 console.log([1,2,3].awesome.sum()   // i want to sum up all array items

but this approach doesn't work as you know how i can achieve something like that

 const array = [1, 2, 3]; Array.prototype.sum = function() { return this.reduce((sum , key)=> sum + key ) } console.log(array.sum())

Multiple Property

 const array = [1, 2, 3, 4]; const objectFunctions = { sum: { value: function() { return this.reduce((cS, key) => cS + key) } }, multiply: { value: function() { return this.reduce((cS, key) => cS * key) } } } Object.defineProperties(Array.prototype, objectFunctions ); console.log(array.multiply()); console.log(array.sum())

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