javascript --- > typeof方法和instanceof方法

ES5中:
原始类型包括:Number、String、Boolean、Null、Undefined
原始封装类型包括:Number、String、Boolean
引用类型包括:Array、Function、RegExp、Error、Date、Error

变量对象
原始类型的实例成为原始值,它直接保存在变量对象中.
引用类型的实例成为引用值,它作为一个指针保存在变量对象内,该指针指向实际对象在内存中的存储位置.

检测方法
原始类型使用:typeof方法
引用类型使用:instanceof方法,(Array使用Array.isArray())

// 原始类型
console.log(typeof "Nicholas");  // "string"
// 引用类型
var s = {} ;
console.log(s instanceof Object);  // true=
// 数组检测
var arr = [];
console.log(Array.isArray(arr)); // true

原始封装类型的特点
在赋值时会自动创建实例,并立即销毁

var name = "Nicholas";
var firstChar = name.charAt(0);
console.log(firstChar);
// javascript引擎执行
var name = "Nicholas";
var temp = new String(name);   // 自动创建实例
var firstChar = temp.charAt(0);
temp = null;  // 销毁
console.log(firstChar);

// 使用instanceof操作符检测不出.
console.log(name instanceof String);  // false

内部属性[[Class]]

// 检测引用类型除了使用instanceof之外,还可以使用Object.prototype.toString来查看
console.log(Object.prototype.toString.call([1,2,3]));
console.log(Object.prototype.toString.call( /regex-literal/i ));
console.log(Object.prototype.toString.call(null));
console.log(Object.prototype.toString.call(undefined));
console.log(Object.prototype.toString.call("abc"));
console.log(Object.prototype.toString.call(42));
console.log(Object.prototype.toString.call(true));

在这里插入图片描述
书上原话:所有typeof返回值为"object"的对象都包含一个内部属性[[Class]].这个属性无法直接访问,一般通过Object.prototype.toString来查看

参考《JavaScript面向对象精要》第一章
参考《你不知道的JavaScript》P34~P35

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值