Sachin
Sachin

Reputation: 2361

TypeError: Cannot set property <function> of undefined

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

TypeError: Cannot set property 'functWriteToLogFile' of undefined

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');
}

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?

EDIT :

I am calling this function in following way :

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


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

Upvotes: 0

Views: 3405

Answers (1)

Blue Skies
Blue Skies

Reputation: 2975

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.


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

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

Upvotes: 4

Related Questions