krl
krl

Reputation: 5296

Object methods vs functions and encapsulation in JavaScript

In class-based object oriented languages one of the benefits of objects is encapsulation: every method of an object has access to the object's data.

In JavaScript this benefit of encapsulation doesn't seem to be the same because of the feature of this.

In the example below method1 has access to this without additional binding, but method2 does not.

Is there any reason to use an object method instead of a plain function in the example below if we need to bind both method2 and function2 in order to have access to this.args inside them?

// service declaration

function Service(args) {
    this.args = args;
}

Service.prototype.method1 = function(query) {
    ............
    let res1 = service2.get(query).map(this.method2.bind(this)); // option 1
    let res2 = service2.get(query).map(function2.bind(this));    // option 2
    ............
};

Service.prototype.method2 = function(data) {
    // use args from 'this'
}

function function2(data) {
    // use args from 'this'
}

// service use

let service = new Service(args);
service.method1(req.query).

Upvotes: 3

Views: 988

Answers (1)

rioc0719
rioc0719

Reputation: 303

I think you should always use methods instead of using bind(this) because when you use external functions, you need to carry those along with that class. Why not just include them as a method on the class?

Also, I don't get the point of the this.method2.bind(this) call. this.method2 is already bound to this because it is a property of this.

Assuming you know some ES6 from your let statement, you could write your code like this:

class Service {
  constructor(args) {
    this.args = args;
  }
  method1(query) {
    let res1 = Service2.get(query).map(this.method2); //btw, what is Service2 here? Is it just an object with methods or does it need to be initialized?
  }
  method2(data) {
    //use data
  }
}
let service = new Service(args);
service.method1(req.query);

Upvotes: 2

Related Questions