What’s happening in this code with Number objects holding properties and incrementing the number?

后端 未结 10 1319
孤街浪徒
孤街浪徒 2020-12-07 06:57

A recent tweet contained this snippet of JavaScript.

Can someone please explain what is happening in it step by step?

> function dis() { return th         


        
10条回答
  •  [愿得一人]
    2020-12-07 07:20

    It's pretty simple.

    function dis () { return this; }
    

    This returns the this context. So, if you do call(5) you're passing the number as an object.

    The call function doesn't supply arguments, the first argument you give is the context of this. Usually if you want it on it's on context, you give it {} so dis.call({}), which means this in the function is an empty this. However, if you pass 5 it seems it will be converted to an object. See .call

    So the return is object

    When you do five * 5, JavaScript sees the object five as the primitive type, so is equivalent to 5 * 5. Interestingly, do '5' * 5, it still equals 25, so JavaScript is clearly casting under the hood. No changes to the underlying five type is done on this line

    But when you do ++ it will convert the object to the primitive number type thus removing the .wtf property. Because you are affecting the underlying type

提交回复
热议问题