Home >Web Front-end >JS Tutorial >Are Strings and Numbers Really Objects in JavaScript?
Decoding the Enigma of JavaScript Objects
In the realm of JavaScript, the omnipresence of objects often raises questions. While arrays and functions exhibit object-like behaviors, unraveling the enigmatic nature of "Strings" and "Numbers" can be perplexing.
The Elusive Nature of Primitive Values
Contrary to popular belief, not everything in JavaScript is an object. Core elements like strings, numbers, and booleans are classified as primitives, characterized by their immutable nature. Unlike true objects, primitives lack methods and properties.
The Illusion of Objecthood
JavaScript employs a clever trick to make primitives appear object-like. When attempting to access a primitive's property (e.g., s.substring(1, 2)), JavaScript seamlessly creates a wrapper object (e.g., String(s)) that possesses the desired methods. However, this wrapper is short-lived, vanishing as soon as the method execution completes.
Proof: The Unreachable Property
This illusion becomes evident when assigning properties to primitives, which ultimately prove futile. Consider the code:
var s = "foo"; s.bar = "cheese"; alert(s.bar); // undefined
Despite assigning a property to the primitive s, attempting to retrieve it yields undefined. This is because the property is attached to the ephemeral wrapper object, which is discarded upon method completion.
Functions: True Objects
In contrast to primitives, JavaScript functions are legitimate objects, inheriting from the Object prototype. This grants them the ability to possess properties and execute any object-based method.
Property Assignment in Functions
Functions can act as typical objects, allowing property assignment and retrieval:
function foo() {} foo.bar = "tea"; alert(foo.bar); // tea
By understanding the distinction between primitives and legitimate objects in JavaScript, we dispel the confusion surrounding the widespread notion that "almost everything is an object."
The above is the detailed content of Are Strings and Numbers Really Objects in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!