


How does JavaScript realize that basic types have properties and methods like objects?
This article brings you relevant knowledge about javascript, which mainly introduces related issues about basic types having properties and methods like objects, including using basic types as objects and basic Type constructors, etc. Let’s take a look at them together. I hope it will be helpful to everyone.
[Related recommendations: javascript video tutorial, web front-end]
"Attribute method of basic type ”
This article will explore an extremely interesting concept, namely the property methods of basic types. How about it, are you a little confused? Let me tell you slowly~
Preface
In other object-oriented programming languages, such as Java
, C
, attributes are objects The unique concept of , the basic type is the basic type, and there is no concept of attribute method.
Yes, this is another bad idea of JavaScript
. Its engine allows us to use property methods to manipulate basic types of data like objects.
Before explaining this strange feature, we must first clarify what is the difference between basic types and object types?
- What is a basic type
-
JavaScript
A value in a basic type; -
Exists in JavaScript
7
basic types, namely:String
,Number
,Boolean
,BigInt
,Symbol
,null
andundefined
;
-
- What is the object type
- A data packet, use
{ }
Created, can store multiple values; -
JavaScript
There are also other types of objects, such as functions;
- A data packet, use
Object-oriented will be covered. A key feature of introducing objects is encapsulation, which can store all kinds of messy data and methods in one object, thereby reducing the complexity of use.
For example:
let user = { name : "xiaoming", hello() { console.log(`你好,我是${this.name}`); }}user.hello();
We encapsulate the properties and methods of the object user
into an object, so that it is very simple to use, we only need to use obj.attr
method can call methods or properties.
However, doing so involves additional overhead (object-oriented has additional overhead), which is also where the object-oriented language C
is slower than C
.
Using basic types as objects
Problems faced
There are two problems that are difficult to reconcile when using basic types as objects:
- We hope that the operation of basic types can be like using objects, such as
"abc".toUpperCase()
; - Objects have additional overhead, and we hope to maintain the basic types Simple and efficient features;
Solution method
JavaScript
The way to solve the above problems is quite "harmony":
- The basic type is the basic type, providing an independent, single value;
- allows access to
String
,Number
,Boolean Methods and properties of
andSymbol
types; - In order to ensure the completeness of the theory, when using methods and properties of basic types, they are first packaged into objects and then destroyed;
The above rules mean that the basic type is still a basic type, but if we want to access the methods and properties of the basic type, we will wrap the basic type into an object (object wrapper), Destroy it after the visit is complete. To be honest, it sounds a bit ridiculous.
The events behind
For example:
let name = "Trump";console.log(name.toUpperCase());//访问基础类型的方法
The execution results of the above code are as follows:
It seems that there is no big problem, but a lot of things happened. We need to know the following points:
-
name
is a string basic type. There is nothing special about it; - When accessing the
name
attribute method, a special object containing a string value is created. This object has thetoUpperCase
method; - Calling the method of a special object
toUpperCase
Returns a new string; - The special object is destroyed when used up;
The value of the variable itself has not changed, as follows:
The result of compromise
Although the solution is full of compromises (bad ideas), however, The result is still good, and the achievements achieved are as follows:
- 基础类型保持了本身的简单、高效;
- 基础类型通过特殊对象拥有了属性和方法;
- 保持了理论的完整,即只有对象才有属性和方法;
理论上虽然如此,但实际上JavaScript
引擎高度优化了这个过程,我怀疑它根本就没有创建额外的对象。只是在口头上表示自己遵循了规范,好像真的搞了个临时对象一样。
常用方法举例
本文只是简单的介绍基础类型方法的概念,并不对各种方法进行讲解,伴随着教程不断深入,会逐步涉及大量的方法。这里只简单的列举基础类型常用的一些方法和属性。
不同的基础类型,拥有不同的属性方法,以下分类列举:
String
-
length
属性,返回字符串长度console.log("abc".length);
Copy after login以上代码结果如下:
-
indexOf(ch)
方法,返回字符串中第一个字符ch
的下标console.log("abc".indexOf('b'));console.log("abc".indexOf('d'));
Copy after login代码执行结果如下:
当字符存在于字符串返回下标(从
0
开始计),如果找不到就返回-1
。 -
concat(str)
方法,拼接两个字符串let str1 = "hello ";let str2 = "world!";console.log(str1.concat(str2));console.log(str1);console.log(str2);
Copy after login代码执行结果如下:
-
replace(str1,str2)
方法,使用str2
替换str1
let str = "javascript";console.log(str.replace('java','996'));console.log(str);
Copy after login代码执行结果如下:
Number
-
toFixed(num)
方法,四舍五入小数到指定精度console.log(9.3333333.toFixed(3));console.log(9.3333333.toFixed(0));
Copy after login代码执行结果如下:
-
toString()
方法,转数字为字符串3.14.toString();//转为'3.14'console.log((8).toString(2));//转为二进制'1000'console.log((9).toString(2));//转为二进制'1001'console.log((996).toString(16));//转为16进制字符串'3e4'
Copy after login代码执行结果如下:
-
toExponential()
方法,转为指数计数法console.log(3.1415926.toExponential());console.log(3.1415926.toExponential(2));console.log(3.1415926.toExponential(3));
Copy after login代码执行结果如下:
后继章节会展示更多的方法,这里就不过的赘述。
基础类型构造函数(不推荐使用的特性)
和Java
一样,JavaScript
可以通过new
操作符,显式的为基础类型创建“对象包装器”,这种做法是极其不推荐的,这里提出,仅为了知识的完整性。
这种做法存在问题,举例如下:
let num = new Number(0);console.log(typeof num);console.log(typeof 0);
代码执行结果如下:
亦或者,在判断中会出现混淆:
let zero = new Number(0);if (zero) { // zero 为 true,因为它是一个对象 console.log('true');}
代码执行结果如下:
同时,大家不要忘了,不带 new
(关键字)的 String/Number/Boolean
函数可以将一个值转换为相应的类型:转成字符串、数字或布尔值(原始类型)。
例如:
console.log(typeof Number('123'));
注意:
null
和undefined
两种类型没有任何方法
本文小节
除
null
和undefined
以外的基础类型都提供了许多有用的方法;虽然
JavaScript
使用了妥协的实现方式,但取得了较为满意的结果,以较低的成本实现了基础类型的属性和方法调用;
【相关推荐:javascript视频教程、web前端】
The above is the detailed content of How does JavaScript realize that basic types have properties and methods like objects?. For more information, please follow other related articles on the PHP Chinese website!

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
