slee
slee

Reputation: 491

How does the below javascript code work? Can you give me some details?

<button onclick="javascript:this.innerHTML={'true':'Start','false':'Pause'}[G.pause=!!!G.pause];">Pause</button>

If I click the button, it turns to 'start', and it turns to 'pause' when I click again.

I've written another segment like the one above, but it doesn't work as I wish:

<button onclick ="javascript: this.innerHTML{'true':'start','false':'pause'};">pause</button> 

Can anybody tell me why?

Upvotes: -1

Views: 109

Answers (4)

aaaaaaaaaaaa
aaaaaaaaaaaa

Reputation: 3700

I want to add that this piece of code is not an example to follow, declaring a literal object for this purpose makes for slow hard to read code. The ternary operator does exactly what is needed:

<button onclick="this.innerHTML=(G.pause=!G.pause?'Start':'Pause');">Pause</button>

Upvotes: 0

Gabriele Petrioli
Gabriele Petrioli

Reputation: 196002

There is a global variable named G in use.

{'true':'Start','false':'Pause'}

this creates an object with two properties.

one has a name true and a value of 'Start'
the other has a name of false and a value of 'Pause'

putting [G.pause=!!!G.pause] after the object means select an element from that object.
look at the member [] operator

the G.pause=!!!G.pause evaluates to true or false and at the same time assigns the value back to G.pause. This way you toggle the value and also select the relative property from the object.

example at http://www.jsfiddle.net/gaby/DfyYg/1/

Upvotes: 1

draeton
draeton

Reputation: 685

Assume G.pause = false

var obj = {
    'true': 'Start',
    'false': 'Pause'
};

G.pause = !!!G.pause; // assignment, not equivalence

// !!!G.pause == !!!(false) == !!(true) == !(false) == true, so G.pause == true

The next time around, G.pause flips back to false. !!val forces any variable to a primitive boolean, and the third ! negates the result. It's basically a toggle.

obj[true] == obj['true'] == 'Start'

Objects properties in JavaScript can be accessed using array notation, as well.

For this to work, G.pause has to be defined before the onclick handler.

Upvotes: 0

erenon
erenon

Reputation: 19118

There is an object literal defined using curly braces: { and }. It has two field, true and false, and you can refer to them by this indicies.

The G.pause=!G.pause part is an expression involving some unidentified variable G. This expression evaluates to true or false; however, this part seems to be broken. Should be "Pause" != this.innerHTML

By evaluating that expression, you call one of the prevoriusly defined field, and pass its content to the innerHTML call. (Looks like some braces are missing around the parameters)

Upvotes: 1

Related Questions