Hello,
Can anyone help me why prototype using arrow function does not work, but works with ES5 syntax?
My code:
```
// Print a random number from an array (Using ES5 syntax)
Array.prototype.random = function() {
return this[Math.floor((Math.random() * this.length))];
}
let arr = [1, 2, 3, 4, 5]
console.log(arr.random()) // Prints random number
// Using ES6 syntax
Array.prototype.random = () => {
return this[Math.floor((Math.random() * this.length))];
}
let arr1 = [1, 2, 3, 4, 5]
console.log(arr1.random()) // Prints undefined
Can anyone help me why prototype using arrow function does not work, but works with ES5 syntax?
My code:
```
// Print a random number from an array (Using ES5 syntax)
Array.prototype.random = function() {
return this[Math.floor((Math.random() * this.length))];
}
let arr = [1, 2, 3, 4, 5]
console.log(arr.random()) // Prints random number
// Using ES6 syntax
Array.prototype.random = () => {
return this[Math.floor((Math.random() * this.length))];
}
let arr1 = [1, 2, 3, 4, 5]
console.log(arr1.random()) // Prints undefined