一般撰寫的方式:雖然沒有建構物件,但別忘了場景本身就是一個物件,所以下面的撰寫方式已經再使用物件了。
var dataStr="jax";
var loadMc:MovieClip = createEmptyMovieClip("container", this.getNextHighestDepth());
loadMc._x = loadMc._y = 0;
loadMc.visible = false;
var mcLoader:MovieClipLoader = new MovieClipLoader();
mcLoader.addListener(this);
mcLoader.loadClip("vodBlock.swf",loadMc);
function onLoadInit(loadMc:MovieClip) {
loadMc._visible = false;
loadMc.text=this.dataStr;
}
使用 JSON 的撰寫方式:如果只是單純的建立一個物件,下面這個寫法應該是最簡潔的,但這並不是一個很好 ActionScript 風格。
var myObject = {
dataStr:"jax",
loadMc:null,
init:function(){
this.loadMc= createEmptyMovieClip("container", this.getNextHighestDepth());
this.loadMc._x = this.loadMc._y = 0;
this.loadMc.visible = false;
var mcLoader:MovieClipLoader = new MovieClipLoader();
mcLoader.addListener(this);
mcLoader.loadClip("vodBlock.swf",this.loadMc);
},
onLoadInit:function(loadMc:MovieClip) {
loadMc._visible = false;
loadMc.text=this.dataStr;
}
}
myObject.init();
利用 Class 撰寫方式:這是 ActionScript 標準風格的撰寫方式,也比較正規一點。
class MyClass{
var dataStr:String;
var loadMc:MovieClip;
function MyClass(){
this.dataStr="jax"
this.loadMc= createEmptyMovieClip("container", this.getNextHighestDepth());
this.loadMc._x = container._y = 0;
this.loadMc.visible = false;
var mcLoader:MovieClipLoader = new MovieClipLoader();
mcLoader.addListener(this);
mcLoader.loadClip("vodBlock.swf",this.loadMc);
}
function onLoadInit(loadMc:MovieClip) {
loadMc._visible = false;
loadMc.text=this.dataStr;
}
}
new MyClass();
延伸原生 Class 的撰寫方式:如果規劃的好這會是一個很省事的撰寫方式。
class MyMovieClip extends MovieClip{
var dataStr:String;
function MyMovieClip(){
this.dataStr="jax"
this._x = this._y = 0;
this.visible = false;
}
function loadMovieClip(src:String) :MovieClip {
var mcLoader:MovieClipLoader = new MovieClipLoader();
mcLoader.addListener(this);
mcLoader.loadClip(src,this);
return this;
}
function onLoadInit(mc:MovieClip) {
this = MyMovieClip(loadMc);
this._visible = false;
this.text=this.dataStr;
}
}
var loadMc:MyMovieClip = MyMovieClip( createEmptyMovieClip("container", this.getNextHighestDepth()) );
loadMc.loadMovieClip("vodBlock.swf");
物件的撰寫有幾個要點:
- 搞清楚 this 到底是誰?這大概也是入門時最容易被弄到翻過來的問題之一
- 物件的規劃,別寫了半天的『物件導向』跟寫『結構語言』沒什麼分別。