给数组 a 扩展一个方法,使其具备 multiply 方法,详见案例

  1. const a = [1, 2, 3, 4, 5];
  2. a.multiply();
  3. console.log(a); // [1, 2, 3, 4, 5, 1, 4, 9, 16, 25]

1.直接在原型上扩充

  1. const a = [1, 2, 3, 4, 5];
  2. Array.prototype.multiply = function() {
  3. this.splice(this.length, 0, ...this.map(item => item * item));
  4. }
  5. a.multiply();
  6. console.log(a); // [1, 2, 3, 4, 5, 1, 4, 9, 16, 25]

因为 a. proto === Array.prototype 故也可以采用以下写法

  1. const a = [1, 2, 3, 4, 5];
  2. a.__proto__.multiply = function() {
  3. this.splice(this.length, 0, ...this.map(item => item * item));
  4. }
  5. a.multiply();
  6. console.log(a); // [1, 2, 3, 4, 5, 1, 4, 9, 16, 25]

上述解法优点是实现起来较简单,缺点是整个数组都具备了这个方法,如果出题人的本意只是对 a 扩充该方法的话,上述解法就带有侵入性了

2.只对 a 扩充

采用 Object.defineProperty 对 a 扩充一个不可枚举属性

  1. const a = [1, 2, 3, 4, 5];
  2. Object.defineProperty(a, 'multiply', {
  3. value: function() {
  4. this.splice(this.length, 0, ...this.map(item => item * item));
  5. },
  6. enumerable: false,
  7. })
  8. a.multiply();
  9. console.log(a); // [1, 2, 3, 4, 5, 1, 4, 9, 16, 25]

还可以改写 a 的原型对象

  1. // 创建一个对象,让 Array.prototype 作为原型对象
  2. const arrProto = Object.create(Array.prototype);
  3. // multiply 作为 arrProto 的一个方法而不是 Array.prototype 的方法
  4. arrProto.multiply = function() {
  5. this.splice(this.length, 0, ...this.map(item => item * item))
  6. }
  7. const a = [1, 2, 3, 4, 5];
  8. // a 的原型改为 arrProto,而不是 Array.prototype
  9. a.__proto__ = arrProto;
  10. a.multiply()
  11. console.log(a); // [1, 2, 3, 4, 5, 1, 4, 9, 16, 25]
  12. console.log(a.__proto__ === Array.prototype); // false
  13. console.log(a.__proto__ instanceof Array); // true

如果觉得上述写法太啰嗦,也可以尝试 Object.create 第二个参数

  1. const arrProto = Object.create(Array.prototype, {
  2. multiply: {
  3. value: function() {
  4. this.splice(this.length, 0, ...this.map(item => item * item))
  5. },
  6. enumerable: false,
  7. }
  8. });
  9. const a = [1, 2, 3, 4, 5];
  10. // a 的原型改为 arrProto,而不是 Array.prototype
  11. a.__proto__ = arrProto;
  12. a.multiply()
  13. console.log(a); // [1, 2, 3, 4, 5, 1, 4, 9, 16, 25]
  14. console.log(a.__proto__ === Array.prototype); // false
  15. console.log(a.__proto__ instanceof Array); // true