I often use function meta properties, i.e. like this
var func = function(){}
func.meta = "meta";
console.log(func);//output: function func()
console.log(func.meta);//output: "meta"
But when I tried using strings in similar way, it did't work.
var string = "string";
string.meta = "meta";
console.log(string);//output: "string"
console.log(string.meta);//output: undefined
Why and how to fix that?
Your string is a primitive value. It accepts the property because of some magic which temporarily converts it to an object (or you can think of it that way). So the assignment isn't useful after that.
You could use the new String
constructor to create an object you can actually hold on to, but that's very unusual for JavaScript.
var string = new String("string");
string.meta = "meta";
console.log(string);
console.log(string.meta);//output: "meta"
The console output on the string
itself will actually probably not show what you want, but in practice it should work in concatenation as such.
Keep in mind that typeof
will no longer give you "string"
as a result. It will now be "object"
.
Personally, I'd just create a custom constructor if you need to store more than the string itself and then use it with the knowledge that the object is composed of your string and the meta data.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With