Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Functions are cleaner than subclasses #116

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 8 commits into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 10 additions & 7 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -558,8 +558,13 @@ extend JavaScript's native Array method to have a `diff` method that could
show the difference between two arrays? You could write your new function
to the `Array.prototype`, but it could clash with another library that tried
to do the same thing. What if that other library was just using `diff` to find
the difference between the first and last elements of an array? This is why it
would be much better to just use ES2015/ES6 classes and simply extend the `Array` global.
the difference between the first and last elements of an array?

One option is to use ES2015/ES6 classes. Classes are useful when you need state.
Consider writing a simple function if state is not an issue. Also, when extending an object,
features will be limited to instances of that subclass only. Another drawback is
(especially when extending built in globals like Array) that instances must be
created using the 'new' keyword. A better option is to write a stateless function.

**Bad:**
```javascript
Expand All @@ -571,11 +576,9 @@ Array.prototype.diff = function diff(comparisonArray) {

**Good:**
```javascript
class SuperArray extends Array {
diff(comparisonArray) {
const hash = new Set(comparisonArray);
return this.filter(elem => !hash.has(elem));
}
function diff(first, second) {
const hash = new Set(second);
return first.filter(elem => !hash.has(elem));
}
```
**[⬆ back to top](#table-of-contents)**
Expand Down