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).
document(data)?service.method2()instead offunction2.call(service)when it's not necessary to be bound (where there is no big difference)this, gains popularity.