Navigation Menu

Skip to content

Commit

Permalink
Adds wraning about behaviour of Array methods not yet defined in the …
Browse files Browse the repository at this point in the history
…extended array class
  • Loading branch information
tinaheiligers committed Oct 8, 2018
1 parent 9783707 commit 2e16c4e
Showing 1 changed file with 2 additions and 0 deletions.
2 changes: 2 additions & 0 deletions 54 - Extending Arrays with Classes for Custom Collections.md
Expand Up @@ -198,3 +198,5 @@ That's not very good, but let's try using `console.table(movies.topRated())` ins
If you run that in your console, that will give us all of the movies, sorted by the number of stars, in a nice table. You can also pass in `console.table(movies.topRated(2))`, the top two rated movies, and that will bring me a table of the top two rated.

That's really handy if you're able to have an array, but also have methods on front of it. Extending arrays, you can extend any of the native stuff that are built into JavaScript to create your own collections.

Finally, we need to add a word of warning when extending arrays with classes for a custom collection: We're modifying the constructor signature of the extended array, so we can't reply on falling back to 'native' array methods such as `.map()`, `.slice()` on the class instance of the array we're using. Similarly, we can't rely on the behaviour of any other method that returns a new instance of an array if we haven't first defined it's behaviour in the context of teh extended class. The reason for the 'unexpected' behaviour is that Javascript calls the constructor each time it runs `.map()` and that constructor is called with the length of the original array. Since we modified the constructor signature, the new copy of the array won't be what you expected it to be. To use these 'native' methods, you'll have to explicitly define them in the extended class, as we did with the method `.add(arg)`.

0 comments on commit 2e16c4e

Please sign in to comment.