Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- Structuring a NodeJS module - variables and methods
- var newUser = new User();
- var User = require('../lib/user');
- module.exports = function User() {
- var authorized = false;
- var username = undefined;
- var password = undefined;
- var statistics = undefined;
- this.authorized = function() {
- return authorized;
- }
- this.username = function() {
- return username;
- }
- this.statistics = function() {
- return statistics;
- }
- }
- function User() {
- this.authStatus = false;
- this.email;
- this.displayName;
- this.inSession;
- }
- User.prototype.isAuthenticated = function() {
- return(this.authStatus && this.email && this.displayName)
- }
- User.prototype.isInSession = function() {
- return(this.inSession && this.isAuthenticated());
- }
- exports.User = User;
- User.prototype.login = function() {
- db.doDbStuff('get user data query', function(_error, _result) {
- this.username = _result[0].name; //this code will not work
- });
- }
- function User() {
- this.login = function() { //you know
- User.prototype.login = function() {
- var self = this // bind this to self so you have a reference to what `this` was
- db.doDbStuff('get user data query', function(_error, _result) {
- self.username = _result[0].name; // self refers to the original `this`, so this works.
- });
- }
- User.prototype.login = function() {
- db.doDbStuff('get user data query', (function(_error, _result) {
- this.username = _result[0].name; // bind fixes the original `this`, so this also works.
- }).bind(this));
- }
- User.prototype.login = function() {
- var _this = this;
- db.doDbStuff('get user data query', function(_error, _result) {
- _this.username = _result[0].name; //this code will now work
- });
- }
Add Comment
Please, Sign In to add comment