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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With