Implementing interfaces

JS doesn't allow multiple inheritance, and it doesn't provide for implementing interfaces either. However, you can build your own ersatz interfaces by using mixins, using a higher order function (as we saw earlier, in the Producing functions from functions section), but with a class as a parameter, and adding methods (but not properties) to it. Even if you don't get to actually use it, let's look at a short example, because it gives another example of working in a functional way.

Read https://developer.mozilla.org/en-US/docs/Glossary/Mixin for a definition. As an alternative, you can use TypeScript; see https://www.typescriptlang.org/docs/handbook/interfaces.html for the latter.

Let's take our Person class from earlier, once again. Let's imagine a couple of interfaces: one could provide an object with a method that produced the JSON version of itself, and another could tell you how many properties an object has. (OK, none of these examples are too useful, but bear with me; the method we'll use is what matters.) We will define two functions that receive a class as an argument and return an extended version of it as a result:

// Source file: src/class_persons.js

const toJsonMixin = base =>
class extends base {
toJson() {
return JSON.stringify(this);
}
};

const countKeysMixin = base =>
class extends base {
countKeys() {
return Object.keys(this).length;
}
};

Now, we can create a new PersonWithMixins class (not a very good name, is it?) by using these two mixins, and we can even provide a different implementation, as with the .toJson() method. A very important detail is that the class to extend is actually the result of a function call; check it out:

// Source file: src/class_persons.js

class PersonWithTwoMixins extends toJsonMixin(countKeysMixin(Person)) {
toJson() {
// redefine the method, just for the sake of it
return "NEW TOJSON " + super.toJson();
}
}

let p2m = new PersonWithTwoMixins("Jane", "Roe");
console.log(p2m);
console.log(p2m.toJson()); // NEW TOJSON {"first":"Jane","last":"Roe"}
console.log(p2m.countKeys()); // 2

Being able to add methods to an object in this way can be a workaround for the problem of being able to implement interfaces. This is important to show how JS can let you work in an advanced style, seemingly beyond what the language itself provides, so that you won't be feeling that the language hinders you when trying to solve a problem.

Using Flow, we will get to use the usual Java-style implements and interface declarations, but they will only be used for type checking; see the Implementing interfaces section for more details.
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.129.249.105