如何判断对象是否为objectwith.inthename类实例?解决点标识符报错
解决
instanceof判断带点标识符类实例的问题 这问题我之前也碰到过,核心是JavaScript对标识符的解析逻辑和instanceof的要求导致的,咱们一步步拆解解决:
为什么你的写法会报错?
- 直接写
if (myvar instanceof objectwith.inthename)时,JS会把objectwith.inthename解析为访问objectwith变量的inthename属性,但你并没有定义objectwith这个变量,所以会抛出ReferenceError: objectwith is not defined。 - 把
'objectwith.inthename'作为字符串传入时,instanceof要求右侧必须是一个构造函数对象,字符串不符合要求,因此会抛出TypeError: Right-hand side of 'instanceof' is not an object。
针对第三方包返回类的解决方案
因为这个类是第三方包提供的,我们需要根据它的暴露方式选择对应的方法:
方案1:如果类作为某个对象的属性存在(属性名带点)
很多第三方包会把类挂载到一个命名空间对象下,如果这个类的属性名就是'objectwith.inthename',可以用括号访问语法获取构造函数:
// 假设第三方包暴露的命名空间是thirdPartyLib const TargetClass = thirdPartyLib['objectwith.inthename']; if (myvar instanceof TargetClass) { // 你的逻辑代码 }
方案2:如果类挂载在全局作用域
如果第三方包把这个类直接挂在了全局对象(比如浏览器的window,Node.js的global)上,同样用括号访问:
// 浏览器环境 const TargetClass = window['objectwith.inthename']; // Node.js环境 // const TargetClass = global['objectwith.inthename']; if (TargetClass && myvar instanceof TargetClass) { // 这里加个判断避免TargetClass不存在时报错 // 你的逻辑代码 }
方案3:无法直接获取构造函数时,检查构造函数名称或类型标记
如果实在拿不到构造函数本身,可以通过对象的constructor.name或者Object.prototype.toString来判断(注意constructor.name可能被篡改,后者更可靠):
// 方法A:检查constructor.name if (myvar?.constructor?.name === 'objectwith.inthename') { // 你的逻辑代码 } // 方法B:用Object.prototype.toString(更稳定) if (Object.prototype.toString.call(myvar) === '[object objectwith.inthename]') { // 你的逻辑代码 }
内容的提问来源于stack exchange,提问作者myol
相关产品推荐
相关产品推荐

