0

在这里,我正在尝试在 javascript 中构造对象。但我收到运行时错误:

TypeError: Cannot set property 'functWriteToLogFile' of undefined

我的 javascript 对象如下:

function SetAstAppLog(logFolderPath,fileNamePrefix,fileSize,logStreamObject) {
.
.
.
.
    this.functWriteToLogFile = function (fileNamePrefix, message) {
        console.log("functWriteToLogFile " + message);
        var currLogStreamObject =  initLogPath(fileNamePrefix);
        console.log("********************");
        console.log(fileNamePrefix);
        console.log(filePath);
        currLogStreamObject.write(message + '\n');
        this.emit('written');
    };

    initLogPath(fileNamePrefix);// Set log path on creation of new object.
    this.emit('objCreated');
}

我想访问functWriteToLogFile其他功能,例如:

SetAstAppLog.prototype.funcLogErrors = function (fileNamePrefix,errLevel,err,req) {
   //make new json object here then call functWriteToLogFile
   this.functWriteToLogFile(fileNamePrefix, JSON.stringify(logErrorObj));
};


我无法在这里找出我的错误。

谁能帮我解决这个问题?

编辑 :

我通过以下方式调用此函数:

var SetAstAppLog = require('astAppLog')();
var fileSize = 1024;


var objCommLogger = new SetAstAppLog(logFolderPath,logCommFilePrefix,fileSize,logCommMsg);
4

1 回答 1

4

如果thisundefined,您必须处于“严格模式”。如果您不严格,那么this将是全局对象,并且您不会收到错误消息,这将无济于事。


因为this函数中的值是根据你调用函数的方式定义的,而且你似乎很清楚你打算this引用从函数的继承的an,.prototype所以你应该使用调用函数new

var o = new SetAstAppLog(...my args...);

鉴于这行代码,您将立即调用您的模块。

var SetAstAppLog = require('astAppLog')(); // <--invoking

这只有在require('astAppLog')返回一个函数然后返回一个函数时才是正确的。

如果它只是返回您最终想要使用的函数,那么您需要删除尾随括号。

var SetAstAppLog = require('astAppLog'); // <-- assigned, not invoked
于 2013-11-05T16:12:36.183 回答