Flash / Flex / ActionScript/Statement/as — различия между версиями
Admin (обсуждение | вклад) м (1 версия) |
|
(нет различий)
|
Версия 09:19, 26 мая 2010
Use as to check the object type
package{
import flash.display.Sprite;
public class Main extends Sprite{
public function Main(){
var checkout: Checkout = new Checkout();
var d1:Didgeridoo = new Didgeridoo();
var d2:Didgeridoo = new Didgeridoo();
checkout.addItem(d1);
checkout.addItem(d2);
trace(checkout.calculate());
}
}
}
class Checkout {
private var _items:Array;
public function Checkout() {
this._items = new Array();
}
public function addItem(product:IProduct):void {
this._items.push(product);
}
public function calculate():uint {
var tmp:uint = 0;
for(var i:uint=0; i<this._items.length; i++) {
tmp += this._items[i].price;
if(this._items[i] as ICustomizable != null) {
if(this._items[i].customPrint != null) {
tmp += 1;
}
}
}
return tmp;
}
}
interface ICustomizable{
function get customPrint():String;
function set customPrint(s:String):void;
}
interface IProduct {
function get price():uint;
function set price(val:uint):void;
function get name():String;
function set name(val:String):void;
function get description():String;
function set description(val:String):void;
}
class Didgeridoo implements IProduct,ICustomizable {
private var _price:uint = 100;
private var _name:String = "Handpainted Didgeridoo";
private var _description:String = "Imported from Australia";
private var _customP:String = "No";
public function get customPrint():String {
return this._customP;
}
public function set customPrint(val:String):void {
this._customP = val;
}
public function get price():uint {
return this._price;
}
public function set price(val:uint):void {
this._price = val;
}
public function get name():String {
return this._name;
}
public function set name(val:String):void {
this._name = val;
}
public function get description():String {
return this._description;
}
public function set description(val:String):void {
this._description = val;
}
}
Using the as Operator to Cast to Date and Array
package{
import flash.display.Sprite;
public class Main extends Sprite{
public function Main(){
var numbers:Array = [1,2,3]
output(numbers);
}
public function output (msg:Object):void {
if (msg is String) {
trace(msg);
}
if (msg is Array) {
var arr:Array = msg as Array; // "Cast" to Array here
trace(arr.join("\n"));
}
}
}
}