-1

This is my way. First call get an error, second is right

Array.prototype.myEach = function (callback) { // defined my function
 for (let index = 0; index < this.length; index++) {
   const element = this[index];
   callback(element, index)
 }
}
    
['a','b','c'].myEach(console.log) //Cannot read property 'myEach' of undefined
    
new Array('a','b','c').myEach(console.log) // a b c
Scott Marcus
  • 64,069
  • 6
  • 49
  • 71
yohann
  • 1
  • 1
  • 1
    You missed the semicolon `;` after the function definition. And please read [Why is extending native objects a bad practice?](https://stackoverflow.com/questions/14034180/why-is-extending-native-objects-a-bad-practice) – str Nov 26 '18 at 16:30

1 Answers1

1

This is a side-effect of Automatic Semicolon Insertion. Without a semi-colon at the end of your function expression, the JavaScript runtime incorrectly thinks that the next bit of code (the Array literal) is something to be evaluated, the result of which should be used in conjunction with the function.

Place a semi-colon at the end of your function expression and the problem is solved.

Array.prototype.myEach = function (callback) { // defined my function
 for (let index = 0; index < this.length; index++) {
   const element = this[index];
   callback(element, index)
 }
}; // <-- Let the runtime know that this is the end of the expression
    
['a','b','c'].myEach(console.log) //Cannot read property 'myEach' of undefined
    
new Array('a','b','c').myEach(console.log) // a b c
Scott Marcus
  • 64,069
  • 6
  • 49
  • 71