例如,我使用Array。
let arr =[1, 2, 3, 4];
Array.prototype.a = function() {
//code
}
arr.a(); //return [2, 4, 6, 8]
是否可以创建原型属性。它是一个函数,它会使任何元素加倍。
尽管可以修改像Array
这样的内部(内置(对象的.prototype
属性,但这被认为是一种糟糕的做法,因为其他人可能会假设您的更改无效(例如命名冲突(。最好不要管本质。
但是,您可以使用原型继承来扩展内部对象,而无需直接修改它们。
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
在ES2015之前的JavaScript版本中,像Array
这样的内部对象的子类化充满了困难。最接近它的是这样的东西:
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