类型错误:无法设置属性 <function>未定义的 [英] TypeError: Cannot set property <function> of undefined

查看:68
本文介绍了类型错误:无法设置属性 <function>未定义的的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Here, i am trying to construct object in javascript. But i am getting runtime error as :

TypeError: Cannot set property 'functWriteToLogFile' of undefined

我的javascript对象如下:

My javascript object as follow :

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,例如:

I am want to access functWriteToLogFile in other functions like :

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


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


I am not able to find out my mistake here.

谁能帮我解决这个问题?

Can anyone help me to solve this issue?

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

I am calling this function in following way :

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


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

推荐答案

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

If this is undefined, you must be in "strict mode". If you weren't in strict, then this would be the global object, and you'd have not received the error message, which wouldn't be helpful.

因为函数中 this 的值是根据您调用该函数的方式定义的,而且由于您打算让 this 引用继承从函数的 .prototype 开始,您应该使用 new 调用该函数.

Because the value of this in a function is defined based on how you invoke the function, and since it seems clear that you intend for this to reference an that inherits from the .prototype of the function, you should be invoking the function using new.

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

<小时>

给定这行代码,您可以立即调用您的模块.


Given this line of code, you're invoking your module immediately.

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

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

This would only be correct if require('astAppLog') returns a function which would then return a function.

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

If it simply returns the function that you ultimately want to use, then you need to remove the trailing parens.

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

这篇关于类型错误:无法设置属性 &lt;function&gt;未定义的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆