2012-01-07 80 views
2

I內有以下代碼沒有訪問該:從嵌套回調

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

+0

您的hashPassword函數不是異步-.- – Raynos 2012-01-07 16:02:49

+0

@Raynos我做錯了什麼? – 2012-01-07 16:30:15

+0

您應該返回結果或錯誤。沒有必要使用回調,你允許從方法 – Raynos 2012-01-07 16:38:42

回答

8

所以那裏有2溶液對這一

第一髒一個

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

和清潔一個使用綁定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)); 
} 
+0

爲什麼第一個髒? – 2012-01-07 02:34:18

+0

只是一個主觀偏好使用你最喜歡的一個。 – megakorre 2012-01-07 02:36:35

+0

Gotcha。謝謝! – 2012-01-07 02:39:33

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

未經測試,但它應該像這樣工作。