Is it possible to somehow attach additional properties to strings in js? I am picturing something along the lines of
var s = "Hello World";
s.x = 'bar';
console.log(s.x);
Unfortunately, s.x
is undefined
after the assignment.
I know this question seems a little of. Why would you want to attach additional properties to a string after all? In my case the reasoning is as following: I am using a (questionably designed) library, which provides a function to create an xhr request given an url. The url is then passed to a callback function with the result.
Picture the library (xhr
-function) similar to:
var xhr = function(url, cb){
$.ajax({
url: url,
success: function(data){
// do library stuff
// my code goes here
}
})
}
Part of the framework is, that the callback function is not passed as a function but copied into the success handler body. This way I am able to access the url parameter in the my code goes here-section.
Now in my cb-handler, I need additional data other than just the url. Is there a way to hack this on to the url parameter? Unfortunately I can't change the library :(
I was planning to do something like:
var xhr = function(url, cb){
$.ajax({
url: url,
success: function(data){
// do library stuff
// my code goes here
// access url.foo
}
})
}
var url = 'https://example.com'
url.foo = 'bar'
xhr(url);