Guest User

Untitled

a guest
Aug 3rd, 2018
134
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.80 KB | None | 0 0
  1. Structuring a NodeJS module - variables and methods
  2. var newUser = new User();
  3.  
  4. var User = require('../lib/user');
  5.  
  6. module.exports = function User() {
  7. var authorized = false;
  8. var username = undefined;
  9. var password = undefined;
  10. var statistics = undefined;
  11.  
  12. this.authorized = function() {
  13. return authorized;
  14. }
  15. this.username = function() {
  16. return username;
  17. }
  18. this.statistics = function() {
  19. return statistics;
  20. }
  21. }
  22.  
  23. function User() {
  24. this.authStatus = false;
  25. this.email;
  26. this.displayName;
  27. this.inSession;
  28. }
  29.  
  30. User.prototype.isAuthenticated = function() {
  31. return(this.authStatus && this.email && this.displayName)
  32. }
  33.  
  34. User.prototype.isInSession = function() {
  35. return(this.inSession && this.isAuthenticated());
  36. }
  37.  
  38. exports.User = User;
  39.  
  40. User.prototype.login = function() {
  41. db.doDbStuff('get user data query', function(_error, _result) {
  42. this.username = _result[0].name; //this code will not work
  43. });
  44. }
  45.  
  46. function User() {
  47. this.login = function() { //you know
  48.  
  49. User.prototype.login = function() {
  50. var self = this // bind this to self so you have a reference to what `this` was
  51.  
  52. db.doDbStuff('get user data query', function(_error, _result) {
  53. self.username = _result[0].name; // self refers to the original `this`, so this works.
  54. });
  55. }
  56.  
  57. User.prototype.login = function() {
  58. db.doDbStuff('get user data query', (function(_error, _result) {
  59. this.username = _result[0].name; // bind fixes the original `this`, so this also works.
  60. }).bind(this));
  61. }
  62.  
  63. User.prototype.login = function() {
  64. var _this = this;
  65. db.doDbStuff('get user data query', function(_error, _result) {
  66. _this.username = _result[0].name; //this code will now work
  67. });
  68. }
Add Comment
Please, Sign In to add comment