Javascript原始类型和相应的对象 [英] Javascript primitive types and corresponding objects

查看:191
本文介绍了Javascript原始类型和相应的对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Javascript中并非每个数据都是对象。存在一些原始类型,如字符串,数字和布尔值,它们不是对象。对于每种类型,都存在一个构造函数,它输出一个具有类似行为的对象: Number String 布尔。为了混淆问题,实际上可以调用基本类型的方法 - 它们将在此操作期间转换为相应的对象,然后转换回来。例如,一个人可以做

In Javascript not every data is an object. There exist a few primitive types, like strings, numbers and boolean which are not objects. For each of this types there exists a constructor which outputs an object with similar behaviour: Number, String and Boolean. To confuse matters, one actually can call methods on primitive types - they will be converted to the corresponding objects during this operation, and then converted back. For instance one can do

var a = 4.1324;
a.toFixed(1) // outputs 4.1

然而,如果你试图比较原语具有严格相等性的类型和对象,差异显示

Yet if you try to compare primitive types and objects with strict equality, the difference shows up

var a = new Number(4);
var b = 4;
a === b; // False!!!
typeof a; // 'object'
typeof b; // 'number'

实际上,有人试图比较对象,无论如何它们都是不同的:

Actually of one tries to compare objects, they turn out to be different anyway:

var a = new Number(4);
var b = new Number(4);
a === b; // False!!!

(从概念的角度来看,我理解这种区别。对象可以有额外的属性,因此不应该比较相等,除非它们实际上是相同的。所以如果我们想要 4 === 4 我们需要使用一个不是但是,任何充分动态的编程语言都面临着这种困境,但Javscript是我所知道的唯一一种有两种类型 - 一种是对象的而一种不是 - 用于数字或字符串。)

(From a conceptual point of view I sort of understand the distinction. Objects can have additional properties, hence the should not compare to equal unless they are actually the same. So if we want to have 4 === 4 we need to use a type which is not an object. But this dilemma is faced by any sufficiently dynamic programming language, yet Javscript is the only one I know where there are two types - one objectful and one not - for numbers or strings.)


为数字,字符串和布尔值保留两个单独的表示形式有什么好处?在什么情况下需要区分原始类型和对象?

What is the advantage of keeping two separate representations for numbers, strings and booleans? In what context could one need the distinction between primitive types and objects?


推荐答案


为数字保留两个
单独的表示形式有什么好处,
字符串和布尔值?

What is the advantage of keeping two separate representations for numbers, strings and booleans?

性能


在什么情况下,人们需要
区分基本类型
和对象?

In what context could one need the distinction between primitive types and objects?

考虑到Coersion。 0 == false 新号码(0)!= false

Coersion comes to mind. 0 == false while new Number(0) != false

例如:

var a = new Boolean(false);
if(a) {
  //this code runs
}

但是

var a = false;
if(a) {
  //this code never runs
}

您可以在此处阅读有关coersion的更多信息: http:// webreflection。 blogspot.com/2010/10/javascript-coercion-demystified.html

You can read more about coersion here: http://webreflection.blogspot.com/2010/10/javascript-coercion-demystified.html

这篇关于Javascript原始类型和相应的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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