代码之家  ›  专栏  ›  技术社区  ›  James Deschênes

Javascript是否可以创建特定对象的原型数组?

  •  1
  • James Deschênes  · 技术社区  · 7 年前

    你好世界

    我想创建一个阵列的原型。

    Array.prototype.foo = function(){}
    

    但我的原型必须仅在该数组仅包含“bar”之类的特定对象时应用 是否可以在javascript中创建这样的原型

    Array<bar>.prototype.foo = function(){}
    

    非常感谢。 詹姆斯

    4 回复  |  直到 7 年前
        1
  •  2
  •   Ele    7 年前

    不,你不能。

    可以检查当前数组中的类型。

    class Bar {}
    
    Array.prototype.foo = function() {
      if (this.some((n) => !(n instanceof Bar))) throw new Error('Incompatible type.');
      
      console.log('called');
    }
    
    let array = [1, 2];
    try {
      array.foo();
    } catch(e) {
      console.log(e.message);
    }
    
    array = [new Bar(), new Bar()];
    array.foo();
        2
  •  1
  •   Guillaume Georges    7 年前

    一种方法是检查数组是否包含 bar 在做任何其他事情之前,如果没有,则停止:

        Array.prototype.foo = function(){
        	if (this.indexOf('bar') === -1) {
        		throw "The array must contain bar";
        	}
        	// do what must be done
          console.log("all good");
        }
        
        var rightOne = ['john', 'jane', 'bar'];
        var wrongOne = ['john', 'jane'];
        
        rightOne.foo();
        wrongOne.foo();
        
        3
  •  0
  •   Cogwizzle    7 年前

    我想你也可以做类似的事情。我认为最好的方法是用一个附加函数来修饰默认JavaScript数组。下面是显示打印功能工作的示例。

    let test = ['a', 'b', 'c'];
    
    function decoratedArray(args) {
      let decorated = [...args];
      decorated.print = () => {
        decorated.forEach((arg) => {
          console.log(arg);
        });
      }
      
      return decorated;
    }
    
    test = decoratedArray(test);
    
    test.print();
        4
  •  0
  •   synthet1c    7 年前

    使用ES6类,您可以对数组进行子类化,以获取其所有内部方法,并向其中添加您自己的方法,而无需修改本机数组原型。

    class Bar {
      constructor(id) {
        this.id = id
      }
    }
      
    class Foo extends Array {
      constructor(...args) {
        super(...args)
      }
      foo() {
        if (this.some(x => x instanceof Bar === false))
          throw new Error('Foo can only contain Bar instances')
        console.log('All items are Bars')
        return this
      }
    }
    
    const pass = new Foo(new Bar(1), new Bar(2))
    const fail = new Foo(new Bar(3), new Object)
    
    pass.foo()
    fail.foo()