'binding method in javascript classes
I have a confusing binding issue about javascript classes in node.js .
in a project, it have two type of using the classes: module1 and module2.
1th module1codes:
const controller = require('app/http/controllers/controller.js');
class homeController extends controller {
index(req,res){
res.send(this.message());
}
message(){
return ('<p> i am home controller.js</p>');
}
}
module.exports = new homeController();
because of, enable to use method of homeController.index, it inherits the auto-bind from controller module.
if we do not use of auto-bind, when use method of homeController.index it will give error that, the message() is undefined.
so far it is ok!
but, in bellow module, it do not use of auto-bind, but the method of helpers.getObjects works correctly!
it do not gives the error that, the auth() is undefined!
2th modulecodes:module.exports = class Helpers { constructor(req,res) { this.req = req; this.res = res; } //how works without extending the auto-bind?! getObjects() { return { auth: this.auth()}; } auth() { return { check: this.req.isAuthenticated(), user: this.req.user } } }
in other word, i expect, the helpers.getObjects, only when works( it when can receive the auth() method, that it extends the auto-bind, just like modulecode(1), but it works without that!
it confused me!
what id difference?
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
