1

I'd like to know how to add a custom function to the array object using prototype.

I called my function get. get takes an index and returns the element from the array with that index. It's pointless i know, but im using it for educational purposes.

So this is how it'd look like using it.

const a = ['1' , '2' , '3'];

a.get(2) -----> returns '3'

This is what i've tried.

Array.prototype.get = index => {
    return this[index];
};

let a = ['1','2' ,'3'];

console.log(a.get(1)); 

This returns undefined to me.

Kevin.a
  • 4,094
  • 8
  • 46
  • 82

2 Answers2

1

By using arrow function you can't bind "this" so in the context of the prototype this equals to "window".

Try this:

Array.prototype.get = function(index){
    return this[index];
};
EladBash
  • 95
  • 6
  • So i tried returning this. It doesnt return the window object, i dont think this equals to window in an arrow function. It returned an empty object instead – Kevin.a Jun 11 '19 at 15:00
  • 2
    @Kevin.a In your function, `this` refers to the context in which the function was declared, which I'd imagine *is* `Window`. [I've made a demo](https://jsfiddle.net/6zpsnL4d/). – Tyler Roper Jun 11 '19 at 15:09
0

I would strongly discourage you from extending/overwriting native JavaScript internals. There are many reasons it's a dangerous practice and it will definitely cost you a lot in future, which happened few years ago to one of the well-known JS frameworks, called Prototype:

In April 2010, blogger Juriy 'kangax' Zaytsev (of Prototype Core) described at length the problems that can follow from monkey patching new methods and properties into the objects defined by the W3C DOM.[5] These ideas echo thoughts published in March 2010 by Yahoo! developer Nicholas C. Zakas They have been summarized as follows:

  • Cross browser issues: host objects are not subject to rules, non-compliant IE DOM behavior, etc.
  • Chance of name collisions
  • Performance overhead

More info

Khashayar
  • 1,321
  • 10
  • 9
  • While I agree with this, it doesn't really make an attempt to answer the question. If you want to discourage what OP is asking for, that's fine of course, however as an *answer*, it should at least provide an alternative. In its current state, this would be more appropriate as a comment (perhaps with a link to the article instead of a quote). – Tyler Roper Jun 11 '19 at 15:04
  • The link to the Wikipedia page is there... See "More info"! – Khashayar Jun 11 '19 at 15:05
  • I know. I'm saying that a general warning should be a *comment* instead of an *answer*, as you've made no attempt to answer the question that was asked. – Tyler Roper Jun 11 '19 at 15:06