thomas,

<<
Number.prototype.whatAmI = function() { return typeof(this); };
var x = 1;
x.whatAmI();
"object"
typeof(x)
"number"
>>

var x = 1  .... is the same as ... var x = Number(1)

So in both cases x.whatAmI is going to refer to Number.prototype which is
indeed of type [object Number] or as typeof reports it as "object" while x
is going to refer to the primitive type returned by Number() or as typeof
reports it  as"number"

On the other hand, if you say:

var x = new Number(1) ....... then the 'this' in whatAmI will refer to an
instance of Number which is also of type [object Number] which means
'typeof x' will be "object" not "number" and will be consistent (in its
String representation) with the output of x.whatAmI().

In this case the primitive type passed to the Number constructor (i.e. 1)
is going to be placed behind an accessor called 'valueOf()' so you can do
x.valueOf() to get 1

The point I wanted to make is 'this' without 'new' will refer to the object
the function is defined on be it 'window' or whatever object.

Intuitive, no? but I would not call this a WTF moment, although JS has so
many....

:)




On Mon, Sep 7, 2015 at 4:55 AM, Thomas Heller <th.hel...@gmail.com> wrote:

> For a little JavaScript WTF and one reason why things are the way the are:
>
> Number.prototype.whatAmI = function() { return typeof(this); };
> var x = 1;
> x.whatAmI();
> "object"
> typeof(x)
> "number"
>
> Fun times debugging that ...
>
> Cheers,
> /thomas
>
> --
> Note that posts from new members are moderated - please be patient with
> your first post.
> ---
> You received this message because you are subscribed to the Google Groups
> "ClojureScript" group.
> To unsubscribe from this group and stop receiving emails from it, send an
> email to clojurescript+unsubscr...@googlegroups.com.
> To post to this group, send email to clojurescript@googlegroups.com.
> Visit this group at http://groups.google.com/group/clojurescript.
>

-- 
Note that posts from new members are moderated - please be patient with your 
first post.
--- 
You received this message because you are subscribed to the Google Groups 
"ClojureScript" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to clojurescript+unsubscr...@googlegroups.com.
To post to this group, send email to clojurescript@googlegroups.com.
Visit this group at http://groups.google.com/group/clojurescript.

Reply via email to