类型错误: 无法设置未定义的属性<函数>

TypeError: Cannot set property <function> of undefined

本文关键字:属性 函数 未定义 错误 设置 类型      更新时间:2023-09-26

在这里,我正在尝试用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);

如果this undefined,则必须处于"严格模式"。如果您不是严格,那么this将是全局对象,并且您不会收到错误消息,这将没有帮助。


由于函数中 this 的值是根据您调用函数的方式定义的,并且由于您显然打算让this引用从函数.prototype继承的 ,因此您应该使用 new 调用该函数。

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

给定这行代码,您将立即调用模块。

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

仅当require('astAppLog')返回一个函数,然后返回一个函数时,这才是正确的。

如果它只返回您最终要使用的函数,则需要删除尾随参数。

var SetAstAppLog = require('astAppLog'); // <-- assigned, not invoked