【问题标题】:Access an object's property from a callback [duplicate]从回调访问对象的属性[重复]
【发布时间】:2016-06-09 18:50:52
【问题描述】:

在我的 Node.js 脚本中,我需要从回调中访问对象的属性(这里是“模型”对象的属性“错误”)。我看到编辑这个属性是不可能的,但是我需要它来抛出一个错误并停止脚本(如果'error'属性有一个值,'construct'函数返回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);
    }
}

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

【问题讨论】:

  • 我猜this 是你的实际问题。你不能那样做。 connect是异步的,还没完成就知道是不是有问题。

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


【解决方案1】:

您在使用“this”时遇到了词法范围问题。在您传递给连接方法的回调函数中,“this”的范围仅限于您正在执行的当前函数,而不是您正在构建的对象。我已经重新构建了您的代码,以便您能够访问您尝试访问的属性......还重新构建了适当的原型继承,消除了对扩展方法的需要......在下面添加了一个示例

看到这个帖子: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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-02-04
    • 2012-09-29
    • 1970-01-01
    • 2018-10-18
    • 1970-01-01
    • 2012-08-05
    • 2011-03-29
    • 2013-12-07
    相关资源
    最近更新 更多