关于前端:类型检查typeof-和-instanceof-运算符区别

7次阅读

共计 4218 个字符,预计需要花费 11 分钟才能阅读完成。

作者:Dmitri Pavlutin
译者:前端小智
起源:Dmitri Pavlutin

点赞再看 ,微信搜寻【大迁世界】 关注这个没有大厂背景,但有着一股向上踊跃心态人。本文 GitHub https://github.com/qq44924588… 上曾经收录,文章的已分类,也整顿了很多我的文档,和教程材料。**

最近开源了一个 Vue 组件,还不够欠缺,欢送大家来一起欠缺它,也心愿大家能给个 star 反对一下,谢谢各位了。

github 地址:https://github.com/qq44924588…

智米们必定晓得,JS 是种弱类型语言,对变量的类型没有限度。

例如,如果咱们应用字符串类型创立了一个变量,前面又能够为同一变量调配一个数字:

let message = 'Hello'; // 调配一个字符串

message = 14; // 调配一个数字

这种动态性为咱们提供了灵活性并简化了变量申明。

不好方面,咱们永远不能确保变量蕴含某种类型的值。例如,以下函数 greet(who) 须要一个字符串参数,然而,咱们能够应用任何类型的参数来调用该函数:

function greet(who) {return `Hello, ${who}!`
}

greet('World'); // => 'Hello, World!'
// You can use any type as argument
greet(true);    // => 'Hello, true!'
greet([1]);     // => 'Hello, 1!'

有时咱们须要在 JS 中查看变量的类型,要怎么做?

应用 typeof 运算符以及 instanceof 来查看实例类型。

1.typeof运算符

在 JS 中,根本类型有 StringNumberBooleanSymbol 等。此外,还有函数、对象和非凡值 undefinednull

typeof是用于确定 expression 类型的运算符:

const typeAsString = typeof expression;

expression 的计算结果是咱们要查找的类型的值。expression 能够是变量 myVariable,属性拜访器myObject.myProp,函数调用myFunction() 或数字 14

typeof expression,取决于 expression 的值,后果可能为:'string''number''boolean''symbol''undefined''object''function'

咱们来看看 typeof 运算符每种类型的状况:

A) String:

const message = 'hello!';
typeof message; // => 'string'

B) Number:

const number = 5;
typeof number; // => 'number'

typeof NaN;    // => 'number'

C) Boolean:

const ok = true;
typeof ok; // => 'boolean'

D) Symbol:

const symbol = Symbol('key');
typeof symbol; // => 'symbol'

E) undefined:

const nothing = undefined;
typeof nothing; // => 'undefined'

F) Objects:

const object = {name: 'Batman'};
typeof object; // => 'object'

const array = [1, 4, 5];
typeof array; // => 'object'

const regExp = /Hi/;
typeof regExp; // => 'object'

G) Functions:

function greet(who) {return `Hello, ${who}!`
}

typeof greet; // => 'function'

1.1 typeof null

如上咱们看到的,用 typeof 判断对象后果是 'object'

然而,typeof null也会计算为'object'

const missingObject = null;
typeof missingObject; // => 'object'

typeof null'object' 是 JS 初始实现中的一个谬误。

因而,在应用 typeof 检测对象时,须要另外查看null

function isObject(object) {return typeof object === 'object' && object !== null;}

isObject({name: 'Batman'}); // => true
isObject(15);                 // => false
isObject(null);               // => false

1.2 typeof 和未定义的变量

尽管 typeof expression 通常决定于 expression 的类型,但也能够应用 typeof 来确定是否定义了变量。

// notDefinedVar is not defined
notDefinedVar; // throws ReferenceError

typeof有一个不错的属性,当 typeof 评估未定义变量的类型时,不会引发 ReferenceError 谬误:

// notDefinedVar is not defined
typeof notDefinedVar; // => 'undefined'

变量 notDefinedVar 没有在以后作用域内定义。然而,typeof notDefinedVar不会抛出援用谬误,而是将后果计算为 'undefined'

咱们能够应用 typeof 来检测是否未定义变量,如果typeof myVar === 'undefined'true,则 myVar 未定义。

2. instanceof 运算符

应用 JS 函数的通常办法是通过在其名称后增加一对括号来调用它:

function greet(who) {return `Hello, ${who}!`;
}

greet('World'); // => 'Hello, World!'

greet('World')是惯例函数调用。

JS 函数能够做更多的事件:它们甚至能够结构对象!要使函数结构对象,只需在惯例函数调用之前应用 new 关键字:

function Greeter(who) {this.message = `Hello, ${who}!`;
}

const worldGreeter = new Greeter('World');
worldGreeter.message; // => 'Hello, World!'

new Greeter('World')是创立实例 worldGreeter 的结构函数调用。

如何查看 JS 是否应用特定构造函数创立了特定实例?应用 instanceof 运算符:

const bool = object instanceof Constructor;

其中 object 是对对象求值的表达式,而 Constructor 是结构对象的类或函数,instanceof计算为布尔值。

worldGreeter实例是应用 Greeter 构造函数创立的,因 此 worldGreeter instanceof Greeter计算结果为true

从 ES6 开始,能够应用 class 来定义对象。例如,定义一个类Pet,而后创立它的一个实例myPet:

class Pet {constructor(name) {this.name = name;}
}

const myPet = new Pet('Lily');

new Pet('Lily')是创立实例 myPet 的结构调用。

因为 myPet 是应用 Pet 类结构的 -const myPet = new Pet('Lily'), 所以 myPet instanceof Pet 的后果为 true

myPet instanceof Pet; // => true

然而,一般对象不是 Pet 的实例:

const plainPet = {name: 'Zoe'};
plainPet instanceof Pet; // => false

咱们发现 instanceof 对于确定内置的非凡实例 (如正则表达式、数组) 很有用:

function isRegExp(value) {return value instanceof RegExp;}
isRegExp(/Hello/); // => true
isRegExp('Hello'); // => false

function isArray(value) {return value instanceof Array;}
isArray([1, 2, 3]); // => true
isArray({prop: 'Val'}); // => false

2.1 instanceof 和父类

当初,Cat 扩大了父类Pet

class Cat extends Pet {constructor(name, color) {super(name);
    this.color = color;
  }
}

const myCat = new Cat('Callie', 'red');

不出所料,myCatCat 类的实例:

myCat instanceof Pet; // => true

但同时,myCat也是基类 Pet 的一个实例:

myCat instanceof Pet; // => true

3. 总结

JS 是一种弱类型的语言,这意味着对变量的类型没有限度。

typeof expression能够用来查看 expression 的类型,后果是可能是其中的一个:'string''number''boolean‘,'symbol''undefined''object''function'

typeof null的值为 'object',因而应用typeof 检测对象的正确办法是typeof object ==='object'&& object!== null

instanceof运算符让咱们确定实例的构造函数。如果 objectConstructor的实例,则 object instanceof Constructortrue


代码部署后可能存在的 BUG 没法实时晓得,预先为了解决这些 BUG,花了大量的工夫进行 log 调试,这边顺便给大家举荐一个好用的 BUG 监控工具 Fundebug。

原文:https://dmitripavlutin.com/ja…

交换

文章每周继续更新,能够微信搜寻 【大迁世界】 第一工夫浏览,回复 【福利】 有多份前端视频等着你,本文 GitHub https://github.com/qq449245884/xiaozhi 曾经收录,欢送 Star。

正文完
 0