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


a recent tweet contained snippet of javascript.

can please explain happening in step step?

> function dis() { return } undefined > 5 = dis.call(5) number {[[primitivevalue]]: 5} > five.wtf = 'potato' "potato" > five.wtf "potato" > 5 * 5 25 > five.wtf "potato" > five++ 5 > five.wtf undefined > five.wtf = 'potato?' "potato?" > five.wtf undefined > 5 6 

in particular, not clear me:

  • why result of dis.call(5) number kind of [[primitivevalue]] property, results of five++ , five * 5 appear plain numbers 5 , 25 (not numbers)
  • why five.wtf property disappears after five++ increment
  • why five.wtf property no longer settable after five++ increment, despite five.wtf = 'potato?' assignment apparently setting value.

op here. funny see on stack overflow :)

before stepping through behaviour, important clarify few things:

  1. number value , number object (a = 3 vs a = new number(3)) different. 1 primitive, other object. cannot assign attributes primitives, can objects.

  2. coercion between 2 implicit.

    for example:

    (new number(3) === 3)  // returns false (new number(3) == 3)   // returns true, '==' operator coerces (+new number(3) === 3) // returns true, '+' operator coerces 
  3. every expression has return value. when repl reads , executes expression, displays. return values don't mean think , imply things aren't true.

ok, here go.

original image of javascript code

the pledge.

> function dis() { return } undefined > 5 = dis.call(5) [number: 5] 

define function dis , call 5. execute function 5 context (this). here coerced number value number object. important note in strict mode this not have happened.

> five.wtf = 'potato' 'potato' > five.wtf 'potato' 

now set attribute five.wtf 'potato', , 5 object, sure enough accepts simple assignment.

> 5 * 5 25 > five.wtf 'potato' 

with five object, ensure can still perform simple arithmetic operations. can. attributes still stick? yes.

the turn.

> five++ 5 > five.wtf undefined 

now check five++. trick postfix increment entire expression evaluate against original value and then increment value. looks five still five, expression evaluated five, set five 6.

not did five set 6, coerced number value, , attributes lost. since primitives cannot hold attributes, five.wtf undefined.

> five.wtf = 'potato?' 'potato?' > five.wtf undefined 

i again attempt reassign attribute wtf five. return value implies sticks, in fact not because five number value, not number object. expression evaluates 'potato?', when check see not assigned.

the prestige.

> 5 6 

ever since postfix increment, five has been 6.


Comments

Popular posts from this blog

magento2 - Magento 2 admin grid add filter to collection -

Android volley - avoid multiple requests of the same kind to the server? -

Combining PHP Registration and Login into one class with multiple functions in one PHP file -