是值是原始的还是盒装的 [英] Does a matter whether a value is primitive or boxed

查看:76
本文介绍了是值是原始的还是盒装的的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可以使用 typeof 来确定值是原始值还是装箱值。

One can use typeof to determine whether a value is primitive or boxed.

考虑:

typeof "foo"; // "string"
typeof new String("foo"); // "object"

Object.prototype.toString结合使用我们可以定义以下两个函数

In combination with Object.prototype.toString we could define the following two functions

var toString = Object.prototype.toString;

var is_primitive_string = function(s) {
  return toString.call(s) === "[object String]" && typeof s === "string";
};

var is_boxed_string = function(s) {
  return toString.call(s) === "[object String]" && typeof s === "object";
};

这两个函数是否有任何用例? (或类似的函数数字布尔等)。

Are there any use cases for these two functions? (Or similar functions for Number, Boolean, etc).

此问题背后的概念来自以下 TJCrowder的评论

The concept behind this question came from the following Comment by T.J.Crowder.

我们是否应该关心我们拥有的价值是原始的还是盒装的?

Should we ever care whether a value we have is primitive or boxed?

推荐答案

我说几乎没有意义,你几乎不关心你是否正在处理 string primitive或 String object。

I'd say there's virtually no point, you almost never care whether you're dealing with a string primitive or a String object.

有边缘情况。例如, String 对象是一个实际对象,您可以向其添加属性。这可以让你做这样的事情:

There are edge cases. For instance, a String object is an actual object, you can add properties to it. This lets you do things like this:

function test(arg) {
    arg.foo = "bar";
}

如果调用代码传递字符串 原语

var s1 = "str";
test(s1);

... arg 升级为 String object并获取添加的属性,但<$ c后,任何内容都不会使用 String 对象$ c> test 返回。

...arg gets promoted to a String object and gets a property added to it, but that String object isn't used by anything after test returns.

相反,如果调用代码传入 String object

In contrast, if calling code passes in a String object:

var s2 = new String("str");
test(s2);

...然后该属性被添加到该对象,调用代码可以看到它。考虑(实时副本):

...then the property is added to that object and the calling code can see it. Consider (live copy):

var s1, s2;

s1 = "str";

display("[Before] typeof s1.foo = " + typeof s1.foo);
test(s1);
display("[After] typeof s1.foo = " + typeof s1.foo);

s2 = new String("str");

display("[Before] typeof s2.foo = " + typeof s2.foo);
test(s2);
display("[After] typeof s2.foo = " + typeof s2.foo);

function test(arg) {
  arg.foo = "bar";
}

输出:

[Before] typeof s1.foo = undefined
[After] typeof s1.foo = undefined
[Before] typeof s2.foo = undefined
[After] typeof s2.foo = string

请注意 s2.foo 是一个字符串,但 s1 .foo 不是(因为 s1 是一个字符串 primitive ,当我们在<$中提升它时创建的对象c $ c> test 与调用代码无关。)

Note that s2.foo is a string, but s1.foo isn't (because s1 was a string primitive, the object created when we promoted it in test has nothing to do with the calling code).

这有什么用例吗?不知道。如果是这样的话,我会说这将是一个非常前卫的边缘案例。

Is there any use case for this? Dunno. I'd say it would be an extremely edgy edge case if so.

这篇关于是值是原始的还是盒装的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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