Limits on Property Additions to JavaScript Primitives
When confronted with a code that cannot add properties to a string primitive, it is essential to understand the fundamental nature of JavaScript primitives. In JavaScript, there are eight distinct types: seven primitive types and one non-primitive type:
Primitive Types:
Non-Primitive Type:
Values associated with primitive types are known as primitive values and lack the ability to hold properties. Conversely, values of the Object non-primitive type are referred to as objects and can possess properties.
Property Assignment Behavior
When assigning a property to a variable, such as:
<code class="js">foo.bar = 'abc';</code>
the outcome depends on the type of foo's assigned value:
Any other type:
Therefore, assigning properties only makes sense for objects.
Case Specific: Cannot Extend String Primitive with Date Property
In the provided example, the variable test contains a value of type String. Thus, attempting to add a property fails.
<code class="js">test.test = "test inner";</code>
Workarounds for Sorting Dates on a Grid
If modifying the code to bind to date objects directly is impractical, consider these alternative solutions:
The above is the detailed content of Why Can\'t I Add Properties to a JavaScript String?. For more information, please follow other related articles on the PHP Chinese website!