1

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);
niklasfi
  • 15,245
  • 7
  • 40
  • 54
  • Strings are one of the primitive types, ie. not objects so you can't attach properties to them like this. – jakeehoffmann Mar 30 '17 at 09:29
  • to attach props to string, use concat or join. str.concat('?bar=a&baz=c') – FrankCamara Mar 30 '17 at 09:29
  • you'd have s as an object rather than a string or a function (otherwise you're mutating the expected behaviour of the string and that's unexpected and somewhat poor design) – Denis Tsoi Mar 30 '17 at 09:29
  • also this question is a possible duplicate of [Why can't I add properties to a string object in javascript?](http://stackoverflow.com/questions/5201138/why-cant-i-add-properties-to-a-string-object-in-javascript) – Denis Tsoi Mar 30 '17 at 09:30
  • Possible duplicate of [Why can't I add properties to a string object in javascript?](http://stackoverflow.com/questions/5201138/why-cant-i-add-properties-to-a-string-object-in-javascript) – niklasfi Mar 30 '17 at 09:49

1 Answers1

1

according to skilldrick on duplicate SO Question why can i add new attr to string obj

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!

I still wouldn't advice it tho; (not exactly intuitive behaviour)

Community
  • 1
  • 1
Denis Tsoi
  • 9,428
  • 8
  • 37
  • 56