提问人:Shahryar Saljoughi 提问时间:6/20/2021 更新时间:6/21/2021 访问量:229
如何在Javascript中获取此关键字的类型?[复制]
How to get type of this keyword in Javascript? [duplicate]
问:
我正在操作原型,以便我可以添加一些扩展方法。
我发现运算符总是在操作数为:Object
typeof
object
this
Object.prototype.logType = function () { console.log(typeof this); }
"Hello".logType()
上面代码的输出是 而不是 .我知道在JavaScript中,一切都确实是一个,但是我需要知道值的确切类型。我怎样才能做到这一点?object
string
object
this
答:
当你在基元上调用一个方法时,JS 会自动将该基元包装在其关联对象包装器中,因此:
"Hello".logType()
成为:
new String("Hello").logType()
因此,在 logType 函数内部引用包装的基元值,为您提供一个对象。你可以调用 .valueOf()
来获取包裹在对象中的原始值:this
Object.prototype.logType = function () { console.log(typeof this.valueOf()); }
"Hello".logType(); // string
(1).logType(); // number
true.logType(); // boolean
1n.logType(); // bigint
Symbol().logType(); // symbol
(() => {}).logType(); // function
({}).logType(); // object
或者,您可以按照注释中的建议使用严格模式,因为它保持原始原语:this
Object.prototype.logType = function () { "use strict"; console.log(typeof this); }
"Hello".logType(); // string
(1).logType(); // number
true.logType(); // boolean
1n.logType(); // bigint
Symbol().logType(); // symbol
(() => {}).logType(); // function
({}).logType(); // object
评论
this.constructor.name
class
.valueOf()
object
)
true
(new class String {}).logType()
this.constructor === String
`${typeof this.valueOf() === this.constructor.name.toLowerCase()?'#':''}${this.constructor.name}`
- 将输出实际的字符串,并且只输出类字符串...或用于 XXX 类等 - 如果您想要该级别的粒度#String
String
XXX
当在严格模式之外传递时,您会遇到非常罕见的情况,即您会遇到包装对象形式(“盒装”)的基元,例如:this
String
因此,您可以使用而不是 来检查您的方法是否是在字符串上调用的。如果要区分继承自 的字符串和对象,可以改用。this instanceof String
typeof this === 'string'
String
this.constructor === String
要获取“常规”字符串(或 的数字,或布尔值 ,等等),您可以调用Number
Boolean
this.valueOf()
(这意味着你也可以编写 - 但请注意,这可能会产生误导,因为任何对象都可以从其方法返回一个字符串,而实际上最初并不是一个字符串。typeof this.valueOf()
valueOf
注意:您无法以这种方式区分 和,因为您获得的是任一方式的实例。'abc'.yourMethod()
new String('abc').yourMethod()
String
(也很有趣:似乎对于像 BigInt
或 Symbol
这样的较新类型,您无法手动创建这样的包装器实例,新的 BigInt(1n)
将失败。但是(function () { return this }).call(1n)
会实现相同的效果,尽管我不知道为什么有人会想要它......
综上所述:获得您想要的确切行为(即实际字符串)的最简单方法是在严格模式下的上下文中定义您的函数:this
(function {
'use strict'
Object.prototype.logType = function () { console.log(typeof this); }
})()
现在它将按预期工作。
评论