代码之家  ›  专栏  ›  技术社区  ›  Brian Patterson

Javascript自定义数组。原型方法日志“未定义”

  •  0
  • Brian Patterson  · 技术社区  · 2 年前

    所以,我以前从未这样做过,尝试向数组中添加一个方法。原型参见控制台。记录下面的使用说明。它一直告诉我方法没有定义。我不知道我做错了什么。帮助

    到目前为止,我最好的结论/猜测是,“this”指的是全局对象,不知怎么搞砸了。但如何解决这个问题,没有线索(

    const solution = input =>{
      
      Object.defineProperty(
          Array.prototype, 'polyReverse', {
            value: () => this ? (polyReverse(this.substr(1)) + this[0]) : (this),
            configurable: true, writable: true  
          }
      );
    
      console.log("string".split("").polyReverse().join(""));
    
    };
    /*****
     * 
     * ReferenceError: polyReverse is not defined
     *   at Array.value (main.js on line 4:20)
     * 
     * 
     *///////
    

    注意:我也尝试了这个方法,以获得价值。。

    value: () => this ? (this.substr(1).polyReverse() + this[0]) : (this),
    

    而这个。。。

    value: () => this ? (this.polyReverse(this.substr(1)) + this[0]) : (this),
    

    没有运气

    2 回复  |  直到 2 年前
        1
  •  0
  •   Aneesh    2 年前

    我尝试了以下方法,并且能够解决 not defined

    Array.prototype.polyReverse = function(value) {
      return this ? (this.substr(1).polyReverse() + this[0]) : (this)
    };
    
    console.log("string".split("").polyReverse().join(""));

    除此之外,你的逻辑似乎有一些问题,它抛出了一个错误。我不确定你想用什么来实现目标 polyReverse ,所以你是修复这个逻辑的最佳人选。

    因为你特别问过 未定义 问题,上面的代码片段应该可以解决您的问题,并帮助您进一步修复逻辑

        2
  •  0
  •   Brian Patterson    2 年前

    因此,根据这里有帮助的人的建议,我能够解决这个问题,正如大家所说的,不要使用箭头函数。对另外,请注意扩展本机方法是多么糟糕!现在我将制作一个子类来做这个。

    谢谢大家的帮助。

    工作代码。。。

    const solution = input =>{
      
      Object.defineProperty(
          Array.prototype, 'polyReverse', {
            value: function() {
              console.log(this); 
              return (this.length > 0 ? 
               (this.join("").substr(1).split("").polyReverse() + this[0]) : 
               (this)
              )},
            configurable: true, 
            writable: true  
          }
      );
    
      console.log("string".split("").polyReverse());
    
    };