0

I use Array for instance.

let arr =[1, 2, 3, 4];


Array.prototype.a = function() {
    //code        
}
arr.a();  //return [2, 4, 6, 8]

Is it possible to create prototype property. And it's a function, it will double any element .

12
  • 2
    Yes, you may do so Commented Mar 25, 2020 at 8:15
  • 4
    @CertainPerformance - it's always good to get permission :p Commented Mar 25, 2020 at 8:15
  • 5
    You could do that, but usually you should not (unless you do it on your own types). Commented Mar 25, 2020 at 8:17
  • 1
    Note that if you add something to Array prototype, then all arrays will have this .a, even ones that does not need it. It may lead to side effects Commented Mar 25, 2020 at 8:21
  • 1
    @TTT this references to the value, [1, 2, 3, 4] in your case. Commented Mar 25, 2020 at 8:28

1 Answer 1

-1

Although you can modify the .prototype property of intrinsic (built-in) objects like Array, it is considered poor practice because other people might make assumptions that your change invalidates (eg. naming collisions). It's best to leave the intrinsics alone.

You can, however, use prototypical inheritance to extend intrinsic objects, without modifying them directly.

class MyArray extends Array {
    static [Symbol.species] = Array
    *[Symbol.iterator]() {
        for(let x = 0; x < this.length; x++) { yield this[x]*2 }
    }
}

const log = console.log
const arr = new MyArray(1,2,3)
console.log([...arr]) // 2,4,6
log(arr.map((i) => i) instanceof MyArray) // false
log(arr.map((i) => i) instanceof Array) // true

In versions of JavaScript prior to ES2015, subclassing intrinsic objects like Array was fraught with difficulty. The closest you could come to it was something like this:

function MyArray() {
    [].push.apply(this, arguments)
    //... plus tens of lines of code managing the `length` property 
}
Object.defineProperty(MyArray, Symbol.species, { value: Array })
MyArray.prototype = Object.create(Array.prototype)
MyArray.prototype[Symbol.iterator] = function*() {
    for (let x = 0; x < this.length; x++) {
        yield this[x] * 2
    }
}

const log = console.log
const arr = new MyArray(1,2,3)
log([...arr]) // 2,4,6
log(arr.map((el) => el) instanceof MyArray) // false
log(arr.map((el) => el) instanceof Array) // true

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.