关于typeof 、instanceof 、constructor的用法
来源:互联网 发布:c语言三角形判断 编辑:程序博客网 时间:2024/06/05 20:36
1、 typeof:用于检测基本的数据类型,对于引用类型的数据对象,则都是返回object
例如:
var s="my name is xiaojie";
var b=true;
var n=10;
var x;
function show(){ }
var o=new Object();
var m=null;
var arr=[1,2,3];
var json={'a':1,'b':2};
alert(typeof s) //string
alert(typeof b) //boolean
alert(typeof n) //number
alert(typeof x) //undefined
alert(typeof show) //function
alert(typeof o) //object
alert(typeof m) //object
alert(typeof arr) //object
alert(typeof json) //object
2、instanceof:用于检测引用类型的数据是什么类型的对象,如Array、Object、RegExp等 。使用格式如下
result=variable instanceof constructor
例如:
var arr=[1,2,3];
var json={'a':1,'b':2};
var reg=/\s+/g;
function show(){ }
alert(arr instanceof Array) //true
同时:alert(arr instanceof Object) //true
alert(json instanceof Object) //true
alert(reg instanceof RegExp) //true
同时:alert(reg instanceof Object) //true
alert(show instanceof Function) //true
同时:alert(show instanceof Object) //true
上述内容应该发现:所有引用类型的值都是Object的实例,因此在检测一个引用类型值和Object构造函数时,instanceof 操作符始终会返回true;,如果使用instanceof l来检测基本的数据类型的时候,都返回false.因为基本类型不是对象
3、constructor:该属性是任何对象本身具有的属性,而非继承来的属性。该属性返回对创建此对象的引用。
例如:var arr=new Array();
alert(arr.constructor == Array) //true;
alert(arr.constructor == Object) //false;
function Person()
{
this.name="xiaowang";
}
var person1=new Person();
var person2=new Person();
var test=new Object();
alert(person1.constructor == Person) //true;
alert(person2.constructor == Person) //true;
alert(person2.constructor == Object) //false;
alert(test.constructor == Object) //true;
对于constructor还需要多说一点是,对象的constructor都指向对象构造函数本身。例如
alert(person1.constructor)
结果为:
//function Person()
//{
//this.name="xiaowang";
//}
至此,typeof 、instanceof 、constructor的基本用法已经介绍完毕,更深入的用法后续更新
- 关于typeof 、instanceof 、constructor的用法
- typeof、instanceof与constructor
- typeof constructor instanceof 判断类型
- javascript之typeof、constructor、instanceof
- typeof + instanceof+toString+constructor是如何判断javascript数据类型的
- js中判断数据类型的属性typeof、instanceof、 constructor、 prototype
- JavaScript 中typeof、instanceof 与 constructor 的区别?
- js typeof,instanceof用法
- typeof和instanceof用法
- typeof()和instanceof()用法
- 关于null的typeof和instanceof
- javascript类型判断 typeof instanceof constructor
- javascript类型判断 typeof instanceof constructor
- javascript 理解 typeof, instanceof and constructor
- 详解js中typeof、instanceof与constructor
- js中typeof、instanceof 和 constructor
- 详解js中typeof、instanceof与constructor
- JS typeof和instanceof用法
- APUE习题10.6(父子进程同步)
- Eclipse新建项目 在drawable下没有xml模板提示记录
- Android自动化测试UiAutomator之环境配置
- 打开exclise在initremoteeditjob时没有响应
- 文件(文件夹) 名称批量提取
- 关于typeof 、instanceof 、constructor的用法
- SpringMvc @requestparam 中文乱码问题解决方案
- 【算法学习】剑指offer问题2——单例模式
- SCRUM:敏捷团队的故事(SCRUM: The Story of an Agile Team)——(2)
- 报错:Ambiguous mapping
- 01背包详解
- Java 学习笔记 Day012(续)
- SAP中使用MM01创建物料如何选定行业领域和物料类型
- Bootstrap—使用按钮组