类型错误: 无法设置未定义的属性<函数>
TypeError: Cannot set property <function> of undefined
在这里,我正在尝试用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
相关文章:
- 如何使对象属性函数成为事件发射器
- 属性函数的 JavaScript 初始值
- 类型错误: 无法设置未定义的属性<函数>
- Javascript set 属性函数不起作用
- 在循环中运行对象属性函数
- 为什么在枚举属性/函数时键长度不准确
- 主干模型获取属性函数返回上次更新的值
- 使用 Jquery 和对象属性函数时出现类型错误
- Javascript:属性函数中的引用
- 导出的目的是什么属性函数在挖空.js库中
- 检查全局属性/函数是否已在 JavaScript 中被覆盖
- 误解了输入文本值属性函数的正确使用
- 将onClick函数绑定到选项卡的href属性函数
- 当函数的属性函数被调用时,是否可以修改函数本身
- 命名对象属性函数
- Javascript -为什么要循环?(原型属性->构造函数属性->函数对象->构造函数属性)
- 如何从属性函数中引用上面的对象
- Javascript继承:子类型原型不能访问超类型的属性/函数
- 破坏性映射对象属性函数
- React.js:如何定义默认属性函数