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);
5
  • Strings are one of the primitive types, ie. not objects so you can't attach properties to them like this. Commented Mar 30, 2017 at 9:29
  • to attach props to string, use concat or join. str.concat('?bar=a&baz=c') Commented Mar 30, 2017 at 9: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) Commented Mar 30, 2017 at 9:29
  • also this question is a possible duplicate of Why can't I add properties to a string object in javascript? Commented Mar 30, 2017 at 9:30
  • Possible duplicate of Why can't I add properties to a string object in javascript? Commented Mar 30, 2017 at 9:49

1 Answer 1

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)

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.