java中typeof_深入剖析JavaScript中的数据类型判断(typeof instanceof prototype.constructor)...

关于JavaScript中的类型判断,我想大部分JavaScripter 都很清楚 typeof 和  instanceof,却很少有人知道 constructor,以及constructor与前面二者的关系

typeof

console.log(typeof 1); //number

console.log(typeof "宋远溪"); //string

console.log(typeof true); //boolean

console.log(typeof {}); //object

console.log(typeof []); //object

console.log(typeof Symbol(1)); //symbol

console.log(typeof null);//object

console.log(typeof undefined); //undefined

console.log(typeof BigInt(1)); //bigint, ES10推出的BigInt是一个内置对象,它提供了表示大于最大安全整数之外的方法, bigint 通常用于计算最大安全整数之外的数值

如你所见,typeof只能进行最基本的类型判断;那我们如果想知道一个变量是对象或者是数组怎么办?接下来

instanceof

console.log ({} instanceof Object); //true

console.log ([] instanceof Array); //true

functionSomething () {}var sth = newSomething();

console.log(sthinstanceof Something); //true

可以看到 instanceof 能区分出数据的类型,以及该数据是由谁创建的,但是,instanceof 就真的万无一失吗?继续往下

functionSomething () {}functionAnything() {}

Something.prototype= newAnything();var sth = newSomething();

console.log(sthinstanceof Something);//true

console.log(sth instanceof Anything);//true

为什么会这样?

因为instanceof 会检查 Anything 是否 存在与 sth 的原型链上,如果存在,则返回True,这么说的话,下面的也是成立的

console.log(sth instanceof Object); //true

constructor

functionSomething() {}functionAnything() {}var template = newAnything();

template.constructor=Something;

Object.defineProperty(template,'constructor',{

enumerable:false,

writable:false,

});

Something.prototype=template;

const sth= newSomething();

console.log(sth.constructor=== Something);//true

console.log(sth.constructor === Anything);//false

console.log(Object.keys(sth)); //[],因为constructor属于内置属性,所以我们配置不可枚举,不可重写;

sth.constructor 其实就是 sth.__proto__.constructor,因为constructor属性存在于原型链上,所以我们可以直接简写;这样就能实现精确1对1比对了

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值