无法从嵌套回调中访问此内容

时间:2012-01-07 02:20:18

标签: javascript node.js

我有以下代码:

var Company = function(app) {
    this.crypto = require('ezcrypto').Crypto;
    var Company = require('../models/company.js');
    this.company = new Company(app);
}

// Create the company
Company.prototype.create = function (name, contact, email, password, callback) {
        this.hashPassword(password, function(err, result) {
            if (err) throw err;
            console.log(this.company); // Undefined
            this.company.create(name, contact, email, result.password, function(err, result) {
                if (err) {
                    return callback(err);
                }
                return callback(null, result);
            });
        });
}

// Get company with just their email address
Company.prototype.hashPassword = function (password, callback) {
    if(typeof password !== 'string') {
        var err = 'Not a string.'
    } else {
        var result = {
            password: this.crypto.SHA256(password)
        };
    }

    if (err) {
        return callback(err);
    }
    return callback(null, result);
}
module.exports = Company;

问题是this.company在该代码块的第11行未定义。

我知道this不是我想的,但我不确定如何重构以获取正确的this

2 个答案:

答案 0 :(得分:8)

所以这个有两个解决方案

首先是脏的

Company.prototype.create = function (name, contact, email, password, callback) {
    var that = this; // just capture this in the clojure <-
    this.hashPassword(password, function(err, result) {
        if (err) throw err;
        console.log(that.company); // Undefined
        that.company.create(name, contact, email, result.password, function(err, result) {
            if (err) {
                return callback(err);
            }
            return callback(null, result);
        });
    });
 }

和使用bind https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Function/bind

的干净的
 Company.prototype.create = function (name, contact, email, password, callback) {
    this.hashPassword(password, (function(err, result) {
        if (err) throw err;
        console.log(this.company); // Undefined
        this.company.create(name, contact, email, result.password, function(err, result) {
            if (err) {
                return callback(err);
            }
            return callback(null, result);
        });
    }).bind(this));
 }

答案 1 :(得分:1)

您可以通过在this范围内声明Company.create来引用// Create the company Company.prototype.create = function (name, contact, email, password, callback) { var me = this; this.hashPassword(password, function(err, result) { if (err) throw err; console.log(me.company); // Undefined - not anymore me.company.create(name, contact, email, result.password, function(err, result) { if (err) { return callback(err); } return callback(null, result); }); }); } ,如下所示:

{{1}}

未经测试,但应该像这样工作。