javascript字符串被解释为对象 [英] javascript string interpreted as object

查看:81
本文介绍了javascript字符串被解释为对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

从生产角度来看可能无关紧要,但我想知道为什么这样做会有所不同。字符串文字被解释为一个对象。

Probably irrelevant from a production standpoint, but I'd like to know why this behaves the way it does. The string literal gets interpreted as an object.

function fancyCallback(callback) {
  callback(this);
  console.log(typeof this); // just to see it really is an object
}

fancyCallback.call('string here', console.log);

我必须致电

this.toString()

。我知道字符串是javascript中的对象(这很可爱),但在简单的console.log('abc')中,它们自然被解释为字符串。这是为什么?这有用吗?请忽略fancyCallback在全局范围内定义的事实!

inside the function if I want the expected output. I know strings are objects in javascript (which is lovely) but in a simple console.log('abc'), they are naturally interpreted as strings. Why is that? Is this useful in any way? Please ignore the fact that fancyCallback is defined in the global scope!

推荐答案

来自 MDN电话()

thisArg

为乐趣调用提供的值。注意,这个
可能不是该方法看到的实际值:如果该方法是非严格模式代码中的
函数,则null和undefined将被全局对象替换为
,并且 原始值将被装箱

The value of this provided for the call to fun. Note that this may not be the actual value seen by the method: if the method is a function in non-strict mode code, null and undefined will be replaced with the global object, and primitive values will be boxed.

原语[aka number / strings ]被放置在容器对象中,因此它就像你看到它一样工作。

Primitives [aka numbers/strings] are placed into a container object, so it is working just like you are seeing it.

所以它基本上做的是

> var x = "string";
> typeof x
"string"
> var temp = new String(x);
> typeof temp
"object"

这篇关于javascript字符串被解释为对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆