Книга: Functional Programming in JavaScript
Назад: 7. Functional and Object-oriented Programming in JavaScript
Дальше: JavaScript's object-oriented implementation – using prototypes

JavaScript – the multi-paradigm language

If object-oriented programming means treating all variables as objects, and functional programming means treating all functions as variables, then can't functions be treated like objects? In JavaScript, they can.

But saying that functional programming means treating functions as variables is somewhat inaccurate. A better way to put it is: functional programming means treating everything as a value, especially functions.

A better way still to describe functional programming may be to call it declarative. Independent of the imperative branch of programming styles, declarative programming expresses the logic of computation required to solve the problem. The computer is told what the problem is rather than the procedure for how to solve it.

Meanwhile, object-oriented programming is derived from the imperative programming style: the computer is given step-by-step instructions for how to solve the problem. OOP mandates that the instructions for computation (methods) and the data they work on (member variables) be organized into units called objects. The only way to access that data is through the object's methods.

So how can these two styles be integrated together?

  • The code inside the object's methods is typically written in an imperative style. But what if it was in a functional style? After all, OOP doesn't exclude immutable data and higher-order functions.
  • Perhaps a purer way to mix the two would be to treat objects both as functions and as traditional, class-based objects at the same time.
  • Maybe we can simply include several ideas from functional programming—such as promises and recursion—into our object-oriented application.
  • OOP covers topics such as encapsulation, polymorphism, and abstraction. So does functional programming, it just goes about it in a different way. So maybe we can include several ideas from object-oriented programming in our functional-oriented application.

The point is: OOP and FP can be mixed together and there are several ways to do it. They're not exclusive of each other.

Назад: 7. Functional and Object-oriented Programming in JavaScript
Дальше: JavaScript's object-oriented implementation – using prototypes

bsn
thank
Vesa Karvonen
I hope you don't mind, but I’d like to point you and your readers to my high-performance optics library for JavaScript that is in production use in multiple projects, has comprehensive support for partial optics and interactive documentation: https://calmm-js.github.io/partial.lenses/ (this takes a moment to load — be patient!)