2

I've seen instances of a variable being both an object and a string. Example:

alert(x + ""); // Hello
alert(x()); // World

This kind of thing is what jQuery does with the $ variable.

How might you get this effect?

6
  • You don't use jQuery's $ like in your first example. jQuery's $ is simply a function which also has properties (which might be functions themselves). The toString mentioned in the answers is rarely useful to override. Commented Aug 14, 2014 at 22:57
  • Are you sure that's what jQuery does? Last time I looked, many (most?) of its methods are overloaded and do stuff depending on whether they are passed a Function, Object, string, whatever, rather than overwriting or replacing built–in methods. Commented Aug 14, 2014 at 22:57
  • Also, jQuery does not override toString (despite it not being useful anyway). You can see that by simply opening the console on SO and typing $.toString() or make sure via $.toString === Function.prototype.toString, which comes out true. Commented Aug 14, 2014 at 23:02
  • jQuery allows you to do $.xyz(); or $(".abc").xyz();. That's what I was talking about. Commented Aug 14, 2014 at 23:04
  • 1
    @tupperkion any function can have properties, because functions are objects. Commented Aug 14, 2014 at 23:07

1 Answer 1

5

No, a variable can't be both an object and a (primitive) string.

However, if you attempt to convert an object to a string (e.g. using obj + ''), the string returned by its toString method is used instead.

function x() {
    return "World";
}
x.toString = function() {
    return "Hello";
};
Sign up to request clarification or add additional context in comments.

1 Comment

And vice versa, primitives are converted to Objects for the sake of evaluation of expressions: 'blah'.split(). ;-)

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.