13.08.2012 Views

ACTIONSCRIPT 3 Developer’s Guide en

ACTIONSCRIPT 3 Developer’s Guide en

ACTIONSCRIPT 3 Developer’s Guide en

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

<strong>ACTIONSCRIPT</strong> 3.0 DEVELOPER’S GUIDE<br />

Using native JSON functionality<br />

MovieClip.prototype.toJSON = function(k):* {<br />

trace("prototype.toJSON() called.");<br />

return "toJSON";<br />

}<br />

Wh<strong>en</strong> your application th<strong>en</strong> calls stringify() on any MovieClip instance, stringify() returns the output of your<br />

toJSON() method:<br />

var mc:MovieClip = new MovieClip();<br />

var js:String = JSON.stringify(mc); //"prototype toJSON() called."<br />

trace("js: " + js); //"js: toJSON"<br />

You can also override toJSON() in native classes that define the method. For example, the following code overrides<br />

Date.toJSON():<br />

Date.prototype.toJSON = function (k):* {<br />

return "any date format you like via toJSON: "+<br />

"this.time:"+this.time + " this.hours:"+this.hours;<br />

}<br />

var dt:Date = new Date();<br />

trace(JSON.stringify(dt));<br />

// "any date format you like via toJSON: this.time:1317244361947 this.hours:14"<br />

Defining or overriding toJSON() at the class level<br />

Applications ar<strong>en</strong>'t always required to use prototypes to redefine toJSON(). You can also define toJSON() as a<br />

member of a subclass if the par<strong>en</strong>t class is not marked final. For example, you can ext<strong>en</strong>d the ByteArray class and define<br />

a public toJSON() function:<br />

package {<br />

}<br />

import flash.utils.ByteArray;<br />

public class MyByteArray ext<strong>en</strong>ds ByteArray<br />

{<br />

public function MyByteArray() {<br />

}<br />

}<br />

public function toJSON(s:String):*<br />

{<br />

return "MyByteArray";<br />

}<br />

var ba:ByteArray = new ByteArray();<br />

trace(JSON.stringify(ba)); //"ByteArray"<br />

var mba:MyByteArray = new MyByteArray(); //"MyByteArray"<br />

trace(JSON.stringify(mba)); //"MyByteArray"<br />

If a class is dynamic, you can add a toJSON property to an object of that class and assign a function to it as follows:<br />

var d:Dictionary = new Dictionary();<br />

trace(JSON.stringify((d))); // "Dictionary"<br />

d.toJSON = function(){return {c : "toJSON override."};} // overrides existing function<br />

trace(JSON.stringify((d))); // {"c":"toJSON override."}<br />

Last updated 6/6/2012<br />

119

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!