如何通过原型传递多维数组?

时间:2017-10-06 08:11:45

标签: javascript

问题

每当我拨打arrayGuide时,我都会收到error

Array.prototype.arrayGuide = function() {
  console.log(this) // When called… this should be getting logged.
}
//How to get this prototype to work


replace = {
  basic: {
    stage1: {
      one: ["hello", "world"],
      two: ["brother", "sister"],
      three: ["baby", "adult"]
    },
    stage2: {
      one: ["1"],
      two: ["2"],
      three: ["3"]
    }
  },
  advanced: {
    humans: [/^biology\s/gi, /science$/i]
  }
}

replace.arrayGuide() // This keeps throwing an error message
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>



结果我应该

我应该从第一个演示中获得这些结果。但出于某种原因,我不是。

function arrayRegExpCreator(place) {
  console.log(place) // I should be getting this…
}

replace = {
  basic: {
    stage1: {
      one: ["hello", "world"],
      two: ["brother", "sister"],
      three: ["baby", "adult"]
    },
    stage2: {
      one: ["1"],
      two: ["2"],
      three: ["3"]
    }
  },
  advanced: {
    humans: [/^biology\s/gi, /science$/i]
  }
}

arrayRegExpCreator(replace)

2 个答案:

答案 0 :(得分:4)

第一个代码段正在扩展Array原型而不是Object。由于replaceObject的一个实例,因此您应该这样做:

Object.prototype.arrayGuide = function() {
  console.log(this) // When called… this should be getting logged.
}

&#13;
&#13;
Object.prototype.arrayGuide = function() {
  console.log(this) // When called… this should be getting logged.
}
//How to get this prototype to work


replace = {
  basic: {
    stage1: {
      one: ["hello", "world"],
      two: ["brother", "sister"],
      three: ["baby", "adult"]
    },
    stage2: {
      one: ["1"],
      two: ["2"],
      three: ["3"]
    }
  },
  advanced: {
    humans: [/^biology\s/gi, /science$/i]
  }
}

replace.arrayGuide() // This keeps throwing an error message
&#13;
&#13;
&#13;

答案 1 :(得分:0)

您正在扩展数组原型,而不是对象原型

将其更改为:

Object.prototype.arrayGuide = function () {
  console.log(this);
}

...也

永远不会扩展原生对象的原型,除非它是polyfill