search
HomeWeb Front-endJS TutorialNot 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:

Copy code The code is as follows:

> 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 ===.

Copy code The code is as follows:

> {} === {}
false

Objects are compared by reference. Only two objects with the same identifier are considered equal.

Copy code The code is as follows:

> 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.

Copy code The code is as follows:

> 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:

Copy code The code is as follows:

> 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.

Copy code The code is as follows:

> "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.

Copy code The code is as follows:

> 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:

Copy code The code is as follows:

value instanceof Constructor

If the above expression returns true, it means value is an instance of Constructor. It is equivalent to:

Copy code The code is as follows:

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:

Copy code The code is as follows:

> "abc" instanceof Object
false
> "abc" instanceof String
false
Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Is JavaScript Written in C? Examining the EvidenceIs JavaScript Written in C? Examining the EvidenceApr 25, 2025 am 12:15 AM

Yes, the engine core of JavaScript is written in C. 1) The C language provides efficient performance and underlying control, which is suitable for the development of JavaScript engine. 2) Taking the V8 engine as an example, its core is written in C, combining the efficiency and object-oriented characteristics of C. 3) The working principle of the JavaScript engine includes parsing, compiling and execution, and the C language plays a key role in these processes.

JavaScript's Role: Making the Web Interactive and DynamicJavaScript's Role: Making the Web Interactive and DynamicApr 24, 2025 am 12:12 AM

JavaScript is at the heart of modern websites because it enhances the interactivity and dynamicity of web pages. 1) It allows to change content without refreshing the page, 2) manipulate web pages through DOMAPI, 3) support complex interactive effects such as animation and drag-and-drop, 4) optimize performance and best practices to improve user experience.

C   and JavaScript: The Connection ExplainedC and JavaScript: The Connection ExplainedApr 23, 2025 am 12:07 AM

C and JavaScript achieve interoperability through WebAssembly. 1) C code is compiled into WebAssembly module and introduced into JavaScript environment to enhance computing power. 2) In game development, C handles physics engines and graphics rendering, and JavaScript is responsible for game logic and user interface.

From Websites to Apps: The Diverse Applications of JavaScriptFrom Websites to Apps: The Diverse Applications of JavaScriptApr 22, 2025 am 12:02 AM

JavaScript is widely used in websites, mobile applications, desktop applications and server-side programming. 1) In website development, JavaScript operates DOM together with HTML and CSS to achieve dynamic effects and supports frameworks such as jQuery and React. 2) Through ReactNative and Ionic, JavaScript is used to develop cross-platform mobile applications. 3) The Electron framework enables JavaScript to build desktop applications. 4) Node.js allows JavaScript to run on the server side and supports high concurrent requests.

Python vs. JavaScript: Use Cases and Applications ComparedPython vs. JavaScript: Use Cases and Applications ComparedApr 21, 2025 am 12:01 AM

Python is more suitable for data science and automation, while JavaScript is more suitable for front-end and full-stack development. 1. Python performs well in data science and machine learning, using libraries such as NumPy and Pandas for data processing and modeling. 2. Python is concise and efficient in automation and scripting. 3. JavaScript is indispensable in front-end development and is used to build dynamic web pages and single-page applications. 4. JavaScript plays a role in back-end development through Node.js and supports full-stack development.

The Role of C/C   in JavaScript Interpreters and CompilersThe Role of C/C in JavaScript Interpreters and CompilersApr 20, 2025 am 12:01 AM

C and C play a vital role in the JavaScript engine, mainly used to implement interpreters and JIT compilers. 1) C is used to parse JavaScript source code and generate an abstract syntax tree. 2) C is responsible for generating and executing bytecode. 3) C implements the JIT compiler, optimizes and compiles hot-spot code at runtime, and significantly improves the execution efficiency of JavaScript.

JavaScript in Action: Real-World Examples and ProjectsJavaScript in Action: Real-World Examples and ProjectsApr 19, 2025 am 12:13 AM

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

JavaScript and the Web: Core Functionality and Use CasesJavaScript and the Web: Core Functionality and Use CasesApr 18, 2025 am 12:19 AM

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Tools

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version