Javascript typeof 和instanceof
1、在Javascript脚本中,如何判断一个变量是什么类型呢?
使用typeof可以来判断变量的类型,类型有object, string, number, boolean,function, undefined。
b= typeof(a)
a=Date,Function,Math,String,Option时, b=function;
a=不存在的对象时,b=undefined。
- //测试1
- function test1(){
- var a = {a:‘test’,b:‘is’,c:‘ok’};
- var f = function(){
- alert(‘a’);
- }
- var s = ‘test is ok’;
- var d = 1234;
- var v;
- document.writeln(typeof a);
- document.writeln(typeof f);
- document.writeln(typeof s);
- document.writeln(typeof d);
- document.writeln(typeof v);
- }
2、如何判断变量的数据类型?这个问题实际上等同于问,该变量是什么类的实例
使用instanceof可以判断一个变量的数据类型,见下面的例子:
- //测试2
- function test2(){
- var a = [];
- var d = new Date();
- var o = {a:‘test’,b:‘is’,c:‘ok’};
- var F = function(){
- }
- var of = new F();
- document.writeln(a instanceof Array);
- document.writeln(d instanceof Date);
- document.writeln(o instanceof Object);
- document.writeln(F instanceof Function);
- document.writeln(of instanceof F);
- }
- test2();
上述例子中的结果均为true,其中of判断其是否是function F的实例,这样的功能非常有用,可用于Javascript面向对象编程中,对象是否是某个自定义类的判断。
3、构造器
在Javascript中对象有构造器方法(均为函数),用于返回器原型,指向函数本身,而非包含函数名的串。
- //测试3
- unction test3(){
- var a = [];
- var d = new Date();
- var o = {a:‘test’,b:‘is’,c:‘ok’};
- var F = function(){
- }
- var of = new F();
- document.writeln(a.constructor + ‘<br>’);
- document.writeln(d.constructor + ‘<br>’);
- document.writeln(o.constructor + ‘<br>’);
- document.writeln(F.constructor + ‘<br>’);
- document.writeln(of.constructor + ‘<br>’);
- }
结果为:
function Array() { [native code] }
function Date() { [native code] }
function Object() { [native code] }
function Function() { [native code] }
function(){ }