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?
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";
};
'blah'.split(). ;-)
$like in your first example. jQuery's$is simply a function which also has properties (which might be functions themselves). ThetoStringmentioned in the answers is rarely useful to 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 outtrue.$.xyz();or$(".abc").xyz();. That's what I was talking about.