JS中区分参数方法

  

实现功能:在使用cocosjs制作游戏过程中,很多东西都可以重复使用,例如菜单栏等等。今天尝试写了一个自定义的Js文件用作菜单方便以后使用。

 

将菜单按钮,以及触发事件作为参数生成一个层 直接在游戏中使用。

 

因此,就需要在封装时候判断参数类型,以减少不必要的麻烦。

--------

 

 

 

 

 

 

 

 

主要:typeof、instanceof、 constructor、 prototyp

如何判断js中的类型呢,先举几个例子:

var a = "iamstring.";

var b = 222;

var c= [1,2,3];

var d = new Date();

var e = function(){alert(111);};

var f = function(){this.name="22";};

 

最常见的判断方法:typeof

alert(typeof a)   ------------> string

alert(typeof b)   ------------> number

alert(typeof c)   ------------> object

alert(typeof d)   ------------> object

alert(typeof e)   ------------> function

alert(typeof f)   ------------> function

其中typeof返回的类型都是字符串形式,需注意,例如:

alert(typeof a == "string") -------------> true

alert(typeof a == String) ---------------> false

另外typeof 可以判断function的类型;在判断除Object类型的对象时比较方便。

 

判断已知对象类型的方法: instanceof

alert(c instanceof Array) ---------------> true

alert(d instanceof Date) 

alert(f instanceof Function) ------------> true

alert(f instanceof function) ------------> false

 

posted @ 2016-01-29 11:18  只猿身在此山中  阅读(269)  评论(0编辑  收藏  举报