gpt4 book ai didi

javascript - 为什么这个转换成对象

转载 作者:行者123 更新时间:2023-11-30 07:45:15 25 4
gpt4 key购买 nike

不是字符串而是对象

String.prototype.foo = function () { return this; };
typeof "hello".foo() // object ???
"hello".foo().toString(); //hello

我猜它应该返回字符串。

最佳答案

没有。一个真正的字符串("hello"'booya')是一个原始值——它没有任何函数或任何东西。这只是一个值。

当你执行 "string".foo 时,它会变成这样:

Object("string").foo

foo 内部,this 指向 Object("string"),而不是原始值。执行 Object("string") 将它变成一个对象,所以 typeof object === 'object'

如果你想要“底层”原语,调用valueOf:

String.prototype.foo = function () {
return typeof this.valueOf();
}
"meep".foo(); //string

关于javascript - 为什么这个转换成对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8013306/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com