[英]Javascript, behavior of instanceof function
I'm creating a Node.js application. 我正在创建一个Node.js应用程序。 I have a project with this structure: 我有一个具有以下结构的项目:
[Project Folder]
|
|---[plc]
| |--- plc.js
| |--- scheduler.js
|
|---[source]
| |--- source.js
|
|---[test]
|--- test.js
The files plc.js , scheduler.js and source.js are "objects", they require other objects and, at the end of file, have an "export" of the object. 该文件plc.js,scheduler.js和source.js是“物”,它们需要其他对象,并在文件末尾,有一个对象的“出口”。 In particular the file plc.js has an weird behavior. 特别是文件plc.js具有奇怪的行为。 First the code: 首先是代码:
var mod_pollist = require('./polling_list.js'); // Polling list.
var mod_operation = require('./operation.js'); // Single operation.
var mod_scheduler = require('./scheduler.js'); // Scheduler object.
var mod_events = require('events'); // Event emitter
var mod_util = require('../util.js'); // Util functions
function plc(comm_driver){
var self = this;
// Other variables are set here
}
// Other functions written as plc.prototype.something = function(parameters){...}
module.exports = plc;
Now the weird behavior: all the other files have at the top of the file the code for importing the plc.js ( var mod_plc = require('../plc/plc.js');
or var mod_plc = require('./plc.js');
for the scheduler) but only in test.js it works correctly, infact if I write 现在这是一种奇怪的行为:所有其他文件在文件顶部都有用于导入plc.js的代码( var mod_plc = require('../plc/plc.js');
或var mod_plc = require('./plc.js');
对于调度程序),但仅在test.js中有效,如果我写
if(PLC instanceof mod_plc)
console.log('yes');
in the file test.js I can find a 'yes' on the console, if I write the same code in the other files I obtain an error: 在文件test.js中 ,如果在其他文件中写入相同的代码,则会在控制台上找到“是”,但会出现错误:
if(PLC instanceof mod_plc)
^
TypeError: Expecting a function in instanceof check, but got #<Object>
at Object.<anonymous> (C:\Users\Massimo\workspace\Scada\plc\scheduler.js:16:
19)
A "temporary solution" could be 一个“临时解决方案”可能是
if(PLC instanceof mod_plc.constructor)
console.log('yes');
but I don't think is the real solution because with all other objects (I've more than 20 files written like plc.js ) this problem doesn't exist. 但是我认为这不是真正的解决方案,因为对于所有其他对象(我编写了20多个文件,如plc.js ),这个问题不存在。
Any suggestion? 有什么建议吗? Do you need more informations? 您需要更多信息吗? Thanks 谢谢
To summarise my comments from above: 总结一下我的意见:
Given that: 鉴于:
TypeError
tells you mod_plc
is an Object
(not a constructor function); TypeError
告诉您mod_plc
是一个Object
(不是构造函数); and 和 mod_plc.constructor
gives you the expected behaviour; 使用mod_plc.constructor
给您预期的行为; it looks like your PLC
variable has somewhere been assigned an instance of mod_plc
(hence is no longer a reference to the expected constructor function). 看起来您的PLC
变量已在某处分配了mod_plc
的实例(因此不再是对预期构造函数的引用)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.