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 offive++
,five * 5
appear plain numbers5
,25
(notnumber
s) - why
five.wtf
property disappears afterfive++
increment - why
five.wtf
property no longer settable afterfive++
increment, despitefive.wtf = 'potato?'
assignment apparently setting value.
op here. funny see on stack overflow :)
before stepping through behaviour, important clarify few things:
number value , number object (
a = 3
vsa = new number(3)
) different. 1 primitive, other object. cannot assign attributes primitives, can objects.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
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.
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
Post a Comment