从回调中访问对象的属性

时间:2016-02-26 14:00:42

标签: javascript node.js oop model-view-controller callback

在我的Node.js脚本中,我需要从回调中访问对象的属性(此处为'错误'' model'对象)。我看到无法编辑此属性,但是我需要它来抛出错误并停止脚本(如果'错误'属性有值,'构造'函数返回false ,错误是在脚本的另一部分抛出的。)

var underscore = require('underscore');
var mysql = require('mysql');
var baseConfig = require('../config/base');

var autoload = require('../autoload');

var core = autoload.load(baseConfig.dirs.core);

module.exports = {
    name: 'model',
    database: null,
    error: null,

    construct: function(host, user, password, database, res) {
        var connection = mysql.createConnection({
            host: host,
            user: user,
            password: password,
            database: database
        });

        connection.connect(function(error) {
            if(error) this.error = error;
        });

        this.database = connection;
        if(this.error) return false;
    },

    extend: function(child) {
        return underscore.extend(this, child);
    }
}

我真的很想知道如何编辑这个属性,因为我还没有找到解决方案。非常感谢你。

1 个答案:

答案 0 :(得分:1)

你有'这个'的词汇范围问题。在回调函数中,您将传递给connect方法'this'的范围限定为您正在执行的当前函数,而不是您正在构建的对象。我重新构建了您的代码,以便您能够访问您尝试访问的属性...还进行了重组以获得正确的原型继承,从而无需使用extend方法...在

请参阅此主题:https://stackoverflow.com/a/32025281/2665925

参考:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/create

var underscore = require('underscore');
var mysql = require('mysql');
var baseConfig = require('../config/base');

var autoload = require('../autoload');

var core = autoload.load(baseConfig.dirs.core);

var dbConfigObj = {
        host: 'localhost',
        user: 'user',
        password: '12345',
        database: 'CarDB'
    }

function DBConnector(config, res){
    var objectScope = this;

    var connection = mysql.createConnection(config);

    connection.connect(function(error) {
        if(error) objectScope.error = error;
    });

    this.database = connection;
    if(objectScope.error) return false;    

}

DBConnector.prototype = {
    name: 'model',
    database: null,
    error: null,

    extend: function(child) {
        return underscore.extend(this, child);
    }
}

DBConnector.prototype.constructor = DBConnector; 

function CarModel(){
    DBConnector.call(this, dbConfigObj);
}

CarModel.prototype = Object.create(DBConnector.prototype,{
    color: {
        value: null //default value,
        writable: true,  
        configurable:true,
    }
})

CarModel.prototype.constructor = CarModel

module.exports = CarModel