加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ActionScript 3 中的as typeof instanceof is的用法

发布时间:2020-12-15 04:10:17 所属栏目:百科 来源:网络整理
导读:1.as 操作符 每一种编程语言都提供强制类型转换,允许你将某一种数据类型转换成另一种数据类型,AS3自然也不例外。但是虽然我编写了不少Flex程序,对 AS3中的强制类型转换还是不太清楚,以前AS中是这样进行强制类型转换的:假设有一个类叫做Class1,我们声明

1.as 操作符

每一种编程语言都提供强制类型转换,允许你将某一种数据类型转换成另一种数据类型,AS3自然也不例外。但是虽然我编写了不少Flex程序,对 AS3中的强制类型转换还是不太清楚,以前AS中是这样进行强制类型转换的:假设有一个类叫做Class1,我们声明了一个它的对象 c1,如果想要将它转换成Class2类型,只要这样写:

Class2(c1);


在AS3中你依然可以这样写,但是AS3 中提供了一个新的操作符: as ,并且推荐使用as 进行强制转换,上述的例子用 as 操作符实现就是这样:

c1 as Class2;


使用 as 操作符有几个好处:

1.它的效果和第一种方法是一样的。

2.如果类型不兼容无法转换,就会返回null,而不是出错。这样你就可以自定义错误的时候该做什么。

3.没有运行时错误(Run Time Error)提示。


不过有些时候我在使用 as 的时候并不能达到强制转换的目的,而使用第一种方法则可以。为什么 as 操作符有时候会不好用呢?这个问题困扰了我很久,知道昨天在MXNA上发现了一篇日志,才恍然大悟:原来在AS3.0类库中最高层类(Top Level classes,所有Top Level classes的列表请看这里)之间进行强制转换时, as 操作符是不起作用的。比如,假如你想要将一个String 类型的字符串 str 转换成 Number 类型的数字 num 时,可能想要这样写:

num = str as Number;

这样写是没有用的,你只能通过第一种方法来达到强制转换的目的:

num = Number(str);

var a:Number=3.1234;
trace(a.toFixed(2) as Number); //null
a=a.toFixed(2) as Number;
trace(a); //0
a=3.1234;
trace(Number(a.toFixed(2))); //3.12


2.typeof

ECMAScript 有 5 种原始类型(primitive type),即 Undefined、Null、Boolean、Number 和 String。

typeof 运算符有一个参数,即要检查的变量或值。例如:

var sTemp = "test string";
alert (typeof sTemp);    //输出 "string"
alert (typeof 86);    //输出 "number"

对变量或值调用 typeof 运算符将返回下列值之一:

undefined - 如果变量是 Undefined 类型的

boolean - 如果变量是 Boolean 类型的

number - 如果变量是 Number 类型的

string - 如果变量是 String 类型的

object - 如果变量是一种引用类型或 Null 类型的


ActionScript3.0测试如下:

var b:Number;
trace(typeof 123); //number
trace(typeof "123"); //string
trace(typeof new Date()); //object
trace(typeof new Array()); //object
trace(typeof undefined); //undefined


3.instanceof is

用于判断一个变量是否某个对象的实例

instanceof==is

mxml对instanceof的警告提示:【3555: 已不再使用 instanceof 运算符,请改用 is 运算符。】

var a:Number=3.1234;
trace(123 is Number); //true
trace("123" is Number); //false
trace("123" is String); //true
trace(new Date() is Date); //true
trace(new Array() is Array); //true
trace(new Object() is Object); //true

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读