如何在Javascript中获取此关键字的类型?

我正在操作的原型,Object以便我可以添加一些扩展方法。
我发现,typeof运营商总是返回object的情况下,操作数是this

Object.prototype.logType = function () { console.log(typeof this); }
"Hello".logType() 

上面代码的输出是object而不是string. 我知道在 JavaScript 中一切都确实是object,但是我需要知道this. 我怎样才能做到这一点?

回答

当你在一个原语上调用一个方法时,JS 会自动将该原语包装在它的关联对象包装器中,所以:

"Hello".logType()  

变成:

new String("Hello").logType() 

因此,this您的 logType 函数内部是指包装的原始值,为您提供一个对象。您可以调用.valueOf()以获取包裹在对象中的原始值:

"Hello".logType()  

或者,您可以按照评论中的建议使用严格模式,因为它保持this原始原始状态:

new String("Hello").logType() 

  • you could also use `this.constructor.name` - which will also work for your own `class`es (`.valueOf()` shows `object`)
  • This will incorrectly return `true` though if I use `(new class String {}).logType()` which is not a string. Better use `this.constructor === String`.

以上是如何在Javascript中获取此关键字的类型?的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>