Not everything in JavaScript is an object_Basics
Although many languages claim: "Everything is an object", in JavaScript, not all values are objects.
Primitive values vs objects
Values in JavaScript can be divided into two major categories: primitive values (primitive) and objects (object).
Definition
Definition of two values in JavaScript:
The values below are the original values.
1. String
2. Number: All numbers in JavaScript are floating point numbers
3. Boolean value
4.null
5.undefined
All other values are objects. Objects can be further divided:
1. Wrapper of original value: Boolean, Number, String. Rarely used directly.
2. Objects created with literals. The following literals produce objects, which can also be created through constructors. You can create objects using literals.
•[] is new Array()
•{} is new Object()
•function() {} is new Function()
•/s*/ is new RegExp("\ s*")
3. Date: new Date("2011-12-24")
Differences
You can define primitives and objects via enumerated primitives and non-primitives. But you can also describe what the primitives and objects are. Let's start with objects.
1. Objects are mutable:
> var obj = {};
> ; obj.foo = 123; // Add attributes and values
123
> obj.foo // Read attributes and return attribute values
123
2. Each object has its own unique identifier, so objects created through literals or constructors are not equal to any other objects, and we can compare them through ===.
> {} === {}
false
Objects are compared by reference. Only two objects with the same identifier are considered equal.
> var obj = {};
> ; obj === obj
true
3. Variables save references to objects, so if two variables apply to the same object - when we change one of the variables, both will also change.
> var var1 = {};
> ; var var2 = var1;
> var1.foo = 123; // Modify the properties of variable val1
123
> var2.foo // val2 also changed
123
As expected, the primitive value is not the same as the object:
1. Primitive values are immutable; you cannot add attributes to them:
> var str = "abc";
> str.foo = 123; // Add attributes (this operation will be ignored)
123
> str.foo // Read the value of the attribute and return undefined
undefined
2. The original value has no internal identifier, and the original value is compared by value: The basis for comparing two original values is their content. If the contents of the two original values are the same, the two original values are considered to be the same.
> "abc" === "abc"
true
这意味着,一个原始值的标识就是它的值,javascript 引擎没有为原始值分配唯一标识。
最后两个事实结合起来的意思是:我们无法区分一个变量到底是对象的引用,还是原始值的副本。
陷阱:原始值和它们的包装类型
规则:忽略尽可能多的包装类型。 在其他编程语言如Java,你很少会注意到他们。
原始值类型 boolean, number 以及 string 都有自己对应的包装类型 Boolean, Number 和 String。 包装类型的实例都是对象值,两种类型之间的转换也很简单:
•转换为包装类型:new String("abc")
•转换为原始类型:new String("abc").valueOf()
原始值类型以及它们相应的包装器类型有很多不同点,例如:
> typeof "abc"
'string'
> typeof new String("abc")
'object'
> "abc" instanceof String
false
> new String("abc") instanceof String
true
> "abc" === new String("abc")
false
包装类型的实例是一个对象,因此和 JavaScript 和对象一样,包装类型也无法进行值的比较(只能比较引用)。
> var a = new String("abc");
> var b = new String("abc");
> a == b
false // 虽然 a 和 b 有相同的内容,但是依然返回 false
> a == a
true
原始值没有自己的方法
包装对象类型很少被直接使用,但它们的原型对象定义了许多其对应的原始值也可以调用的方法。 例如,String.prototype 是包装类型 String 的原型对象。 它的所有方法都可以使用在字符串原始值上。 包装类型的方法 String.prototype.indexOf 在 字符串原始值上也有,它们并不是两个拥有相同名称的方法,而的的确确就是同一个方法:
> "abc".charAt === String.prototype.charAt
true
在数字的包装类型 Number 的原型对象有 toFixed 方法,即 Number.prototype.toFixed,但是当我们写如下代码时却发生错误:
> 5.toFixed(3)
SyntaxError: Unexpected token ILLEGAL
此错误是解析错误(SyntaxError),5 后面跟着一个点号(.),这个点被当作了小数点,而小数点后面应该是一个数,以下代码可以正常运行:
> (5).toFixed(3)
"5.000"
> 5..toFixed(3)
"5.000"
值的分类:typeof 和 instanceof
如果你想要对值进行分类,你需要注意原始值和对象之间的区别。 typeof 运算可以用来区分原始值和对象。instanceof 可以用来区分对象,而且,instanceof 对于所有的原始值都返回 false。
typeof
typeof 可以用来判断原始值的类型,以及区分对象值和原始值:
> typeof "abc"
'string'
> typeof 123
'number'
> typeof {}
'object'
> typeof []
'object'
typeof 返回以下字符串:
参数 | 结果 |
---|---|
undefined | "undefined" |
null | "object" |
布尔值 | "boolean" |
数字 | "number" |
字符串 | "string" |
函数 | "function" |
其他 | "object" |
Note:
•typeof will return "object" when operating on null, which is a bug in the JavaScript language itself. Unfortunately, this bug will never be fixed because too much existing code already relies on this behavior. This does not mean that null is actually an object[4].
•typeof also allows you to check whether a variable has been declared without throwing an exception. No function can do this because you cannot pass an undeclared variable to a function parameter.
> typeof undeclaredVariable
'undefined'
> undeclaredVariable
ReferenceError: undeclaredVariable is not defined
• Functions are also object types; this may not be understood by many people, but sometimes it is very useful.
•An array is an object.
More information about typeof [5] and [6].
instanceof
instanceof can detect whether a value is an instance of a constructor:
value instanceof Constructor
If the above expression returns true, it means value is an instance of Constructor. It is equivalent to:
Constructor.prototype.isPrototypeOf(value)
Most objects are instances of Object because the end of the prototype chain is Object.prototype. The primitive value is not an instance of any object:
> "abc" instanceof Object
false
> "abc" instanceof String
false

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

How to use WebSocket and JavaScript to implement an online speech recognition system Introduction: With the continuous development of technology, speech recognition technology has become an important part of the field of artificial intelligence. The online speech recognition system based on WebSocket and JavaScript has the characteristics of low latency, real-time and cross-platform, and has become a widely used solution. This article will introduce how to use WebSocket and JavaScript to implement an online speech recognition system.

WebSocket and JavaScript: Key technologies for realizing real-time monitoring systems Introduction: With the rapid development of Internet technology, real-time monitoring systems have been widely used in various fields. One of the key technologies to achieve real-time monitoring is the combination of WebSocket and JavaScript. This article will introduce the application of WebSocket and JavaScript in real-time monitoring systems, give code examples, and explain their implementation principles in detail. 1. WebSocket technology

Introduction to how to use JavaScript and WebSocket to implement a real-time online ordering system: With the popularity of the Internet and the advancement of technology, more and more restaurants have begun to provide online ordering services. In order to implement a real-time online ordering system, we can use JavaScript and WebSocket technology. WebSocket is a full-duplex communication protocol based on the TCP protocol, which can realize real-time two-way communication between the client and the server. In the real-time online ordering system, when the user selects dishes and places an order

How to use WebSocket and JavaScript to implement an online reservation system. In today's digital era, more and more businesses and services need to provide online reservation functions. It is crucial to implement an efficient and real-time online reservation system. This article will introduce how to use WebSocket and JavaScript to implement an online reservation system, and provide specific code examples. 1. What is WebSocket? WebSocket is a full-duplex method on a single TCP connection.

JavaScript and WebSocket: Building an efficient real-time weather forecast system Introduction: Today, the accuracy of weather forecasts is of great significance to daily life and decision-making. As technology develops, we can provide more accurate and reliable weather forecasts by obtaining weather data in real time. In this article, we will learn how to use JavaScript and WebSocket technology to build an efficient real-time weather forecast system. This article will demonstrate the implementation process through specific code examples. We

JavaScript tutorial: How to get HTTP status code, specific code examples are required. Preface: In web development, data interaction with the server is often involved. When communicating with the server, we often need to obtain the returned HTTP status code to determine whether the operation is successful, and perform corresponding processing based on different status codes. This article will teach you how to use JavaScript to obtain HTTP status codes and provide some practical code examples. Using XMLHttpRequest

Usage: In JavaScript, the insertBefore() method is used to insert a new node in the DOM tree. This method requires two parameters: the new node to be inserted and the reference node (that is, the node where the new node will be inserted).

JavaScript is a programming language widely used in web development, while WebSocket is a network protocol used for real-time communication. Combining the powerful functions of the two, we can create an efficient real-time image processing system. This article will introduce how to implement this system using JavaScript and WebSocket, and provide specific code examples. First, we need to clarify the requirements and goals of the real-time image processing system. Suppose we have a camera device that can collect real-time image data
