Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Encapsulating methods behind Getters

I'm developing a website using the node.js/express stack and I'm trying to develop in the functional style which is pretty new to me. The express method res.send requires the function to be called as a method because it refers to this in the body, but calling methods doesn't work naturally in the functional style.

You can put the method behind a getter function that turns it into a function, but I don't know if there are any downsides to this other than code complexity?

Example:

(function() {
"use strict";

function Foo() {
  function bar() {
    console.log(this.x);
  }
  return {
    bar,
    get baz() {
      var s = this;
      return () => s.bar();
    }
  }
}

var a = new Foo();
a.x = 5;
a.bar();
a.baz();

var b = a.bar;
var c = a.baz;
//b(); // throws an error because `this` is not defined
c();

function wrapper(f) {
  f();
}

//wrapper(a.bar); // throws an error
wrapper(a.baz);

})();
like image 361
Chris Philip Avatar asked Jun 04 '16 02:06

Chris Philip


People also ask

What are the encapsulation methods?

There are three different methods of chemical encapsulation, namely, coacervation, molecular inclusion [7], and cocrystallization [8]. Physical encapsulation is also known as mechanical encapsulation.

Does getters and setters ensure encapsulation?

Having getters and setters does not in itself break encapsulation. What does break encapsulation is having a getter and a setter for every data member (every field, in java lingo). That is one step away from making all data members public.

How can encapsulation be achieved?

How can Encapsulation be achieved? Explanation: Using access specifiers we can achieve encapsulation. Using this we can in turn implement data abstraction. It's not necessary that we only use private access.


1 Answers

Ultimately it depends on your exact use-case, but adding wrapper functions is pretty typical in javascript and Node and is unlikely to add any downsides. You can fix the error you're seeing when calling wrapper(a.bar); // throws an error with the use of bind, as below:

wrapper(a.bar.bind(a));

Calling bind will ensure that this is set to appropriately when the function is called later.

Here is a demo: https://jsfiddle.net/zuL9g98m/

like image 182
lucasjackson Avatar answered Oct 02 '22 06:10

lucasjackson