|
在JavaScript中typeof和instanceof操作符都可以进行类型检查,那么它们之间有什么差异?本篇文章给大家介绍一下typeof和instanceof操作符的区别。有一定的参考价值,有需要的朋友可以参考一下,希望对大家有所帮助。 
相关推荐:《javascript视频教程》 智米们肯定知道,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 中,基本类型有 String、Number、Boolean和 Symbol 等。此外,还有函数、对象和特殊值undefined和null。 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); // => false1.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' }); // => false2.1 instanceof 和父类 现在,Cat 扩展了父类Pet: class Cat extends Pet {
constructor(name, color) {
super(name);
this.color = color;
}
}
const myCat = new Cat('Callie', 'red');不出所料,myCat是Cat类的实例: 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运算符让我们确定实例的构造函数。 如果object是Constructor的实例,则object instanceof Constructor为true。
原文地址:https://dmitripavlutin.com/javascript-typeof-instanceof/ 作者:Dmitri Pavlutin 译文地址:https://segmentfault.com/a/1190000038312457
更多编程相关知识,请访问:编程课程!! 以上就是JavaScript中类型检查:typeof和instanceof操作符的区别的详细内容,更多请关注模板之家(www.mb5.com.cn)其它相关文章! |