修改 javascript class 属性

Modifying javascript class attributes

我想在这里做的是,我有以下 class 会话

function Session(){
    this.accounts = {};
    this.setupAccounts = function(res){
        this.accounts = res;
        log(res);
        log(this.accounts);
    };

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

class Session 有一个属性accounts,它会保存一定的数据。但是为了初始化它,我将它初始化为一个空对象。

接下来我调用方法setupAccounts来修改accounts的值。例如,我读取一个文件,加载它的数据,然后将该数据存储在帐户中。

但是我遇到了范围问题。

例如下面的代码:

var session = new Session();
var user_account_path = '/adata/user_accounts.json';
loadJsonFile(user_account_path)
     .then(session.setupAccounts);
session.test();

所以我在上面的代码中所做的是将文件的内容作为 Json 对象获取,然后我将该数据传递给方法 setupAccounts 以便将该数据存储在变量帐户中.但我的输出如下所示:

Object {arjrule3: Object}  // printing the json object read from file
Object {arjrule3: Object}  // locally changed value of accounts
console.log(session.accounts) // printing global value of accounts
{} // value has not changed. 

我做错了什么?为什么对象会话的帐户值没有改变?

刚刚发生了一些有趣的事情,如果我编写如下代码:

var session = new Session();
var user_account_path = '/adata/user_accounts.json';
loadJsonFile(user_account_path)
   .then(function(res){
      session.setupAccounts(res);  // Change Here
   });

输出:

Object {arjrule3: Object}
Object {arjrule3: Object}
session.accounts
Object {arjrule3: Object}  // works! Why ?

有效,为什么会这样?

var session = new Session();
var user_account_path = '/adata/user_accounts.json';
loadJsonFile(user_account_path)
 .then(session.setupAccounts);
session.test();

在上面的示例中,您只是将函数 "setupAccounts" 作为回调传递。您需要先绑定它,例如

var session = new Session();
var user_account_path = '/adata/user_accounts.json';
loadJsonFile(user_account_path)
 .then(session.setupAccounts.bind(session));
session.test();

您添加的另一个示例有效,因为您在会话对象上调用 "setupAccounts" 函数,而不仅仅是传递对它的引用。