I was messing around with JavaScript, and noticed that this can never be a primitive. What am I talking about? Let me explain.
Take this function for example.
function test(){
return typeof this;
}
test.call('Abc'); // 'object'
test.call(123); // 'object'
They are both 'object', not 'string' or 'number', like I’d expect.
After a bit of confusion (and messing with instanceof), I figured out what’s going on. 'Abc' is being coverted to a String object, and 123 is being converted to a Number object.
Anyway, my question is why does this happen, and how do I convert an object back to its primitive?
I know I could use (String)this or (Number)this, but how can I do that if I don’t know the type?
EDIT: I was trying to do this:
function element(){
var $e = $(this),
$d = $e.closest('div');
}
element.call('#myID');
and it wasn’t working. this is a String object, and jQuery just made a collection of objects instead of using the selector to search the DOM.
As others noted, it’s coerced to an object as per the spec.
Important thing to note is that if you’re in strict mode, the coercion doesn’t happen.
So the real question is why aren’t you using strict? 😉
As you noted in your comment, you should be able to use
.valueOf()if you’re supporting implementations that don’t support strict mode.If you’re only expecting a String, or if you’re also expecting a Number, but you don’t mind a numeric String instead, you could do this…
If you want to know its type, use the generic
toStringavailable onObject.prototypeto get the internal [[Class]] property.