Why can't I add properties to a string object in javascript?
There are 8 language types in JavaScript:
- 7 primitive types: Undefined, Null, Boolean, Number, BigInt, String, and Symbol
- 1 non-primitive type: Object
Values of the primitive types are called primitive values and they cannot have properties.
Values of the Object non-primitive type are called objects an they can have properties.
When you try to assign a property named 'bar'
to a variable foo
, like so:
foo.bar = 'abc';
then the result will depend on the type of the value of foo
:
(a) if the value of foo
is of the type Undefined or Null, then an error will be thrown,
(b) if the value of foo
is of the type Object, then a named property 'bar'
will be defined on the object foo
(if necessary), and its value will be set to 'abc'
,
(c) if the value of foo
is of any other type, then a TypeError
will be thrown in strict mode: “can't assign to property "bar"
on foo
: not an object”. In loose mode, the above assignment operation will be a no op. In either case, the variable foo
will not be changed in any way.
So, as you can see, assigning properties to variables only makes sense if those variables are objects. If that is not the case, then the assignment will either do nothing at all, or even throw an error.
In your case, the variable test
contains a value of the type String, so this:
test.test = "test inner";
does nothing at all.
However, since ES5 introduced accessor properties, there is an exception to what I've said above. Accessor properties allow us to define functions which are invoked whenever the property is either retrieved or set.
For instance:
var str = '';
str.prop;
Here str
is a variable holding a String value. Therefore, accessing a property of that variable should be a no-op (str.prop
merely returns undefined
). This is true with one exception: if String.prototype
contains a accessor property 'prop'
with a defined getter, then that getter will be invoked.
So, if this is defined:
Object.defineProperty( String.prototype, 'prop', {
get: function () {
// this function is the getter
}
});
then this
str.prop;
will invoke that getter function. This also works in strict mode.
Live demo: http://jsfiddle.net/fmNgu/
However, I don't think that adding accessor properties to the built-in prototypes would be a good practice.
JavaScript - Why can't I add new attributes to a string object?
A string in JavaScript isn't an instance of String
. If you do new String('my string')
then it will be. Otherwise it's a primitive, which is converted to a String
object on the fly when you call methods on it. If you want to get the value of the string, you need to call toString()
, as shown below:
var s = new String("hello world!");
s.x = 5;
console.log(s.x); //5
console.log(s); //[object Object]
console.log(s.toString()); //hello world!
how can i add custom properties to javascript string object
thanks to all of you for your help.but i got the way
Object.defineProperty( String.prototype, 'IsNullOrEmpty', {
get: function () {
return ((0 === this.length) || (!this) || (this === '') || (this === null));
}
});
var str = "";
str.IsNullOrEmpty;//returns true
Cannot add property to Object, how to fix?
The Object is a Mongoose Object. Mongoose Objects have restrictions on their properties which prevent new properties from being added. The solution is to convert the Object to a plain JS Object via MongooseObject.toObject(), or the mongoose lean() function. Answered here:
Can not add additional element to (mongoose) object
add property to a string
As str
is a string literal, str.len = 4
is basically rendered as
var temp = new String(str);
temp.len = 4;
temp = null
As you can see any update applied were temporary and are not available after that line. Hence, as str.len
is undefined, with var strlen1 = str.len
, you assign undefined
to strlen1
var strlen2 = str.len = 4
is basically rendered as
var strlen2 = 4;
str.len = 4;
So as you can see there are 2 different assignment rather than 4 being assigned to str.len
and then str.len
assigned to strlen2
If you want to the first condition to work, make str
a String object. Try following
var str = new String('test1')str.len = 4var strlen1 = str.lenconsole.log('strlen1 = ', strlen1) // will paint 4
Issue in Adding property to string object
The reason you can't add properties or methods to a string literal is that when you try to access a literal's property or method, the Javascript interpreter temporarily copies the value of the string into a new object and then use that object's properties or methods. This means a String literal can only access a string's default properties or methods and those that have been added as prototypes.
More info can be obtained from this link:
http://www.hunlock.com/blogs/The_Complete_Javascript_Strings_Reference
Hope this will help you
Strings are not object then why do they have properties?
A string like "Hello" is not an object in JavaScript, but when used in an expression like
"Hello".indexOf(2)
A new object derived from the constructor function String
is produced wrapping the string "Hello"
. And indexOf
is a property of String.prototype
so things work as expected, even though there is a lot of magic going on.
In the following case
> var s = "xyz"; s.prop = 1; console.log(s.prop);
undefined
The reason you see undefined
is that:
- The variable
s
is given a value which is a primitive string - In
s.prop = 1
and property namedprop
is assigned to a new, anonymous wrapper object. - In the third statment above, another new object is created to wrap the primitive
s
. That is not the same wrapper object as in the second statement, and it does not have aprop
property, soundefined
is produced when asking for its value according to the basic JavaScript rules.
Unable to add a property to an object using either the dot notation or the indexer notation?
Assigning properties to primitive string values does not cause an error. Instead it internally promotes the string type to a String object, performs the assignment and then discards the String object.
The reason for doing this is to enable the use of String.prototype getters and methods on primitive string values. (Similar considerations apply to using Number.prototype methods on primitive number type values)
In your case
this.url = window.location.href;
sets this.url
to a primitive string value. Then when you set url.params
to a function it is internally and effectively treated as
new String(this.url).params = function () ....
for the purposes of the assignment, but the String object created gets discarded after the statement has been executed. The primitive value in this.url
does not gain properties - it is not an object data type and doesn't have properties.
Related Topics
Firing Event on Dom Attribute Change
How to Efficiently Randomly Select Array Item Without Repeats
Determine Original Size of Image Cross Browser
What Does Curly Brackets in the 'Var { ... } = ...' Statements Do
When and Where Does JavaScript Run, How About PHP? How to Combine the Two
Add/Delete Table Rows Dynamically Using JavaScript
How to Create a Custom Scrollbar on a Div (Facebook Style)
How to Upload Image into HTML5 Canvas
JavaScript Regular Expression to Validate Url
How to Use JSON File in HTML Code
How Does Basic Object/Function Chaining Work in JavaScript
Why Does Usestate Cause the Component to Render Twice on Each Update
In JavaScript, Why Is the "This" Operator Inconsistent
How to Get the Mouse Position Without Events (Without Moving the Mouse)
How to Hide Form Code from View Code/Inspect Element Browser
Check a Radio Button with JavaScript