node.js instanceof和cleartextStream

时间:2012-08-19 06:07:30

标签: javascript node.js

我试图验证我的原型的两个参数是否是我期望它们的实例。我需要知道cleartextStream是否是node.js docs调用tls.cleartextStream的实例,以及manager是否是我在另一个文件中定义自己的原型实例。

var tls = require('tls'),
    clientManager = require('./client_manager');

var Client = function (cleartextStream, manager) {
    /*
     * Both arguments must be proper instances of the expected classes.
     */
    if (!(cleartextStream instanceof tls.cleartextStream) || !(manager instanceof clientManager))
        throw (...)

所有"好"到现在。当该位执行时,我得到:

if (!(cleartextStream instanceof tls.cleartextStream) || !(manager instanceof
TypeError: Expecting a function in instanceof check, but got #<CleartextStream>

,对于经理部分:

if (!(cleartextStream instanceof tls) || !(manager instanceof clientManager))
TypeError: Expecting a function in instanceof check, but got [object Object]

那么,我将如何检查这些实例?

编辑:阅读this post后,我发现对象实际上是构造函数的实例,因此将我的代码修改为

if (!(cleartextStream instanceof tls) || !(manager instanceof clientManager.constructor))

实际上解决了第二个问题。不过,第一个仍然存在。

1 个答案:

答案 0 :(得分:0)

tls不会导出这些类供你检查,所以我没有看到一个非常干净的方法来做它。

您可以做的一件事是检查对象的原型是否符合您的预期。

target_proto = new tls.createSecurePair().cleartext.__proto__
if (target_proto !== clearTextStream.proto)
  throw(....)

需要注意的一点是,只有当您和此对象的创建者指的是相同版本的模块(例如,使用相同的路径导入等)时,这才会起作用,以便 proto 对象将相等。