【问题标题】:TypeError: Cannot set property <function> of undefinedTypeError:无法设置未定义的属性 <function>
【发布时间】:2013-11-06 00:29:18
【问题描述】:

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

【问题讨论】:

  • 你能在小提琴中展示你所有的代码吗?这很奇怪。
  • 这与您的其他问题相同。如果您在那边收到的答案不起作用,不要接受它。也就是说,您对该问题的原始答案是错误的,但现在已得到纠正。您的问题是您使用的答案不正确。
  • 显示实际使用“funcLogErrors”函数的代码。

标签: javascript node.js prototype


【解决方案1】:

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


因为函数中this 的值是根据您调用函数的方式定义的,而且很明显您打算让this 引用从函数的.prototype 继承的an,所以您应该使用new 调用函数。

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

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

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

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

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

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

【讨论】:

  • 请找到我更新的问题。这里我正在使用新关键字调用函数。
  • @user2625690:你漏掉了一些东西。如果使用newthis 的值将不是undefined
  • @user2625690:不知道你的模块的结构,我能确定的有限。但是由于某种原因,您会立即调用该模块。 var SetAstAppLog = require('astAppLog')(); 为什么你有最后一个括号?如果模块返回一个函数,这将调用它,给你错误,假设这是你想要的构造函数。如果您不需要调用它,请删除尾随括号。 var SetAstAppLog = require('astAppLog') /* no parens here */;
猜你喜欢
  • 2015-09-09
  • 2021-01-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-06-20
  • 2022-08-16
  • 2018-08-13
相关资源
最近更新 更多