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 .
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 .
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