Javascript Primitives vs. Objects: Clarifying the Notion
Despite the common perception that "almost everything in Javascript is an object," not all entities in the language adhere to this definition. This distinction between primitives and objects warrants clarification.
Primitives
In contrast to objects, primitives are immutable values that exist in their fundamental form. They lack methods and properties, and include data types such as:
Object Wrappers
Primitives have corresponding object wrappers (String, Number, Boolean) that offer methods and properties. However, primitives themselves are not objects. To interact with a primitive's properties, Javascript implicitly creates a wrapper object for the operation.
Example with Strings
Consider the code snippet below:
var s = "foo"; var sub = s.substring(1, 2); // sub is now the string "o"
Javascript internally performs the following steps:
Attempting to Assign Properties to Primitives
Assigning properties to primitives is not effectively possible because any such properties will be associated with the temporary wrapper object and not the primitive itself:
var s = "foo"; s.bar = "cheese"; alert(s.bar); // undefined
Functions as Objects
Functions, on the other hand, are genuine objects capable of inheriting from the Object class. They possess properties and can be manipulated like other objects:
function foo() {} foo.bar = "tea"; alert(foo.bar); // tea
In conclusion, while it may appear that primitives have object-like behavior, they are distinct from true objects in Javascript. Object wrappers allow interactions with primitive values, but primitives remain immutable. Functions, however, are полноценные объекты, fully fledged objects capable of all object capabilities. This understanding clarifies the relationship between primitives and objects in the Javascript language.
The above is the detailed content of Are Javascript Primitives Actually Objects?. For more information, please follow other related articles on the PHP Chinese website!