[Related recommendations: JavaScript video tutorials, web front-end]
This article will explore an extremely interesting concept, namely the attribute methods of basic types. How about it, are you a little confused? Let me tell you slowly ~
In other object-oriented programming languages, such as Java
and C++
, attributes are a unique concept of objects, and the basic type is the basic type. There is no concept of attribute methods.
Yes, it's 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?
JavaScript
;7
basic types in JavaScript
, namely: String
, Number
, Boolean
, BigInt
, Symbol
, null
and undefined
;{ }
Create and can store multiple values;JavaScript
also has other types of objects, such as functions; itwill be covered in object-oriented. A key feature of introducing objects is encapsulation , which can store all kinds of messy data and methods in one object. , thus reducing the complexity of use.
For example:
let user = { name: "xiaoming", hello() { console.log(`Hello, I am ${this.name}`); }}user.hello();
We encapsulate the attributes and methods of the object user
into an object, so that it is very simple to use. We only need to use obj.attr
to call methods or attributes.
However, doing so involves additional overhead (object-oriented has additional overhead), which is also where the object-oriented language C++
is slower than C
as objects There are two problems that are difficult to reconcile when using basic types as objects:
"abc".toUpperCase()
;JavaScript
solves the above problems in a very "simple" way:
String
, Number
, Boolean
and Symbol
Methods and properties of the type;the meaning of the above rules is that the basic type is still a basic type, but what if If we want to access the methods and properties of a basic type, we will wrap the basic type into an object (object wrapper) and then destroy it after the access is complete. To be honest, it sounds a bit ridiculous.
An example
let name = "Trump";console.log(name.toUpperCase());//Methods to access basic types.
The execution results of the above code are as follows:
It seems that there is no big problem, but a lot of things happened, and we need to know the following points:
name
is a basic string type, and there is nothing special about it;name
attribute method, a file containing A special object with a string value. This object has a toUpperCase
method;toUpperCase
returns a new string;the value of the variable itself does not change, as follows:
Although the solution is full of compromises (bad ideas), the result is still good, and the achievements achieved are as follows:
although this is theoretically true, in fact the JavaScript
engine is highly optimized for this process, and I suspect that it does not create additional objects at all. He just verbally stated that he followed the rules, as if he really had a temporary object.
This article only briefly introduces the concept of basic type methods and does not explain various methods. As the tutorial continues to deepen, a large number of methods will gradually be involved. Here we only briefly list some commonly used methods and properties of basic types.
Different basic types have different attribute methods, which are listed in the following categories:
length
attribute, returns the string length
console.log("abc".length);
The results of the above code are as follows:
indexOf(ch)
method returns the subscript of the first character ch
in the string
console.log("abc".indexOf('b'));console.log("abc".indexOf('d'));
The code execution results are as follows:
When the character exists in the string, the index (counted from 0
) is returned, if not found, -1
is returned.
concat(str)
method, splice two strings
let str1 = "hello ";let str2 = "world!";console.log(str1.concat(str2));console.log(str1);console.log(str2 );
The code execution results are as follows:
replace(str1,str2)
method, use str2
to replace str1
let str = "javascript";console.log(str.replace('java','996'));console.log(str);
The code execution results are as follows:
toFixed(num)
method, round decimals to the specified precision
console.log(9.3333333.toFixed(3)); console.log(9.3333333.toFixed(0));
The code execution results are as follows:
toString()
method, convert numbers to strings
3.14.toString();//Convert to '3.14'console.log((8).toString(2));//Convert to binary '1000'console.log((( 9).toString(2));//Convert to binary '1001'console.log((996).toString(16));//Convert to hexadecimal string '3e4'The
code execution results are as follows:
toExponential()
method, converted to exponential counting method
console.log(3.1415926.toExponential()); console.log(3.1415926.toExponential(2)); console.log(3.1415926.toExponential(3));
The code execution results are as follows:
More methods will be shown in subsequent chapters, so I won’t go into details here.
Like Java
, JavaScript
can explicitly create "object wrappers" for basic types through the new
operator. This approach is extremely not recommended . It is mentioned here just for knowledge. of integrity.
There are problems with this approach, for example:
let num = new Number(0);console.log(typeof num);console.log(typeof 0);
The code execution results are as follows:
Or, there will be confusion in the judgment:
let zero = new Number(0);if (zero) { // zero is true because it is an object console.log('true');}
The code execution result is as follows:
At the same time, don’t forget that the String/Number/Boolean
function without new
(keyword) can convert a value to the corresponding type: into a string, a number, or a Boolean value (original type).
For example:
console.log(typeof Number('123'));
Note:
The two types
null
andundefined
do not have any methods.
the basic types other than null
and undefined
provide many useful methods;
although JavaScript
uses a compromised Implementation method, but achieved relatively satisfactory results, realizing the attributes and method calls of basic types at a lower cost;
[Related recommendations: JavaScript video tutorials, web front-end]
The above is how JavaScript realizes that basic types have the same attributes and objects as objects For the details of the method, please pay attention to other related articles on the source code network for more information!