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

后端 未结 10 1336
孤街浪徒
孤街浪徒 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

    Declare function dis. Function returns its context

    function dis() { return this }
    undefined
    

    Call dis with context 5. Primitive values are boxed when passed as context in strict mode (MDN). So five now is object (boxed number).

    five = dis.call(5)
    Number {[[PrimitiveValue]]: 5}
    

    Declare wtf property on five variable

    five.wtf = 'potato'
    "potato"
    

    Value of five.wtf

    five.wtf
    "potato"
    

    five is boxed 5, so it's number and object at the same time (5 * 5 = 25). It doesn't changes five.

    five * 5
    25
    

    Value of five.wtf

    five.wtf
    "potato"
    

    Unboxing five here. five now is just primitive number. It prints 5, and then add 1 to five.

    five++
    5
    

    five is primitive number 6 now, there are no properties in it.

    five.wtf
    undefined
    

    primitives cannot have properties, you can't set this

    five.wtf = 'potato?'
    "potato?"
    

    you can't read this, because it was not set

    five.wtf
    undefined
    

    five is 6 because of post incrementing above

    five
    6
    

提交回复
热议问题