Variable not defined, even if defined

0

I made a class, which saves in a user login and password array:

function AccountManager() {
    this.accounts = {};
}

AccountManager.prototype.createAccount = (login, password) => {
    this.accounts[login] = password;
};

module.exports = AccountManager;

And in index.js, I created a test account:

var accountManager = new lib.AccountManager();
accountManager.createAccount("test", "test");

But it says that accounts is undefined.

this.accounts[login] = password;
                         ^

TypeError: Cannot set property 'test' of undefined

at AccountManager.createAccount (c:\users\natha\documents\visual studio 2017\Projects\WarfaceXmpp\WarfaceXmpp\lib\Utils\AccountManager.js:6:23)
at Object.<anonymous> (c:\users\natha\documents\visual studio 2017\Projects\WarfaceXmpp\WarfaceXmpp\app.js:6:16)
at Module._compile (module.js:571:32)
at Object.Module._extensions..js (module.js:580:10)
at Module.load (module.js:488:32)
at tryModuleLoad (module.js:447:12)
at Function.Module._load (module.js:439:3)
at Timeout.Module.runMain [as _onTimeout] (module.js:605:10)
at ontimeout (timers.js:386:14)
at tryOnTimeout (timers.js:250:5)
    
asked by anonymous 23.05.2017 / 18:30

2 answers

5

I believe that using (login, password) => { causes the behavior to change, instead of accessing this o this of "object" this takes the same value as global (node.js) or window (if it is a browser) , then to adjust do this:

function AccountManager() {
    this.accounts = {};
}
AccountManager.prototype.createAccount = function(login, password) {
    this.accounts[login] = password;
};

AccountManager.prototype.test = function() {
    console.log(this.accounts);
};

var x = new AccountManager();
x.createAccount("test", "test");
x.createAccount("foo", "bar");
x.test("test", "test");
    
23.05.2017 / 18:58
2

Is this code inside a class? The this when within a class is the scope of class properties, commonly defined in constructor() of class ...

class Teste {
    constructor() {
        this.title = 'Mensageria';
    }
    teste(){
        this.title = 'teste' // isso funciona
    }
}

If the class does not exist, the this becomes the function , so the error.

    
23.05.2017 / 18:43