Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Javascript Custom Array.prototype.method logs 'not defined'

So, I’ve never done this before, trying to add a method to the Array.prototype. See console.log statement below for usage. It keeps telling me the method is not defined. I can’t figure out what I’m doing wrong. Help!

My best conclusion / guess so far is that "this" is referring to the global object, and that’s screwing it up somehow. But how to fix that, no clue. 🙁

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)
 * 
 * 
 *///////

NOTE: I also tried this for the value of value..

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

and this …

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

with no luck

>Solution :

I tried the following and was able to resolve the issue of not defined

Array.prototype.polyReverse = function(value) {
  return this ? (this.substr(1).polyReverse() + this[0]) : (this)
};

console.log("string".split("").polyReverse().join(""));

Beyond this your logic seems to have some issue and it is throwing an error. I’m not sure what you are trying to achieve with polyReverse, so you would be the best person to fix that logic.

Since you specifically asked about the not defined issue, the above snippet should solve your problem and help you proceed further to fixing the logic

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading