I was messing around with JavaScript and noticed that this
never be primitive. What I'm talking about? Let me explain.
Take this feature, for example.
function test(){ return typeof this; } test.call('Abc');
They are both 'object'
and not 'string'
or 'number'
, as I expected.
After some confusion (and messing with instanceof
), I realized what was going on. 'Abc'
closed by a String
object, and 123
converted to a Number
object.
In any case, my question is why this happens, and how do I convert an object back to its primitive?
I know I can use (String)this
or (Number)this
, but how to do it if I don't know the type?
EDIT : I tried to do this:
function element(){ var $e = $(this), $d = $e.closest('div'); } element.call('#myID');
and he did not work. this
is a String
object, and jQuery simply created a collection of objects instead of using a selector to search for the DOM.
Rocket hazmat
source share