TypeError:无法设置undefined </function>的属性<function>

时间:2013-11-05 16:03:05

标签: javascript node.js prototype

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

1 个答案:

答案 0 :(得分:4)

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


因为函数中this的值是根据你调用函数的方式来定义的,并且因为你希望this能够引用从.prototype继承的函数。对于该函数,您应该使用new调用该函数。

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

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

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

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

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

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