javascript - 无法从嵌套回调中访问 this

标签 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

最佳答案

所以有两个解决方案

首先是脏的

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));
 }

关于javascript - 无法从嵌套回调中访问 this,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8766800/

相关文章:

javascript - 在javascript中将函数作为参数传递,未定义错误

javascript - 我现有的代码是 javascript,我想在 jquery 中转换它们?

node.js - Express 4 压缩

html - 修复手机上的放大

javascript - 将数组转换为字符串,同时将 [ ] 保留在字符串内

node.js - PassportJS 重命名 "user"对象

node.js - Exceljs 写入文件

javascript - 如何增加 Cloud Firestore 中的计数器

javascript - JSON 到数组不工作

javascript - 带下划线的排序和重组 json 对象