Home >Web Front-end >JS Tutorial >Type checking in JavaScript: the difference between typeof and instanceof operators
In JavaScript both typeof and instanceof operators can perform type checking, so what are the differences between them? This article will introduce to you the difference between typeof and instanceof operators. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to everyone.
Related recommendations: "javascript video tutorial"
Smarties must know that JS is a weakly typed language, and variables are There are no restrictions on the type.
For example, if we create a variable using the string type, we can later assign a number to the same variable:
let message = 'Hello'; // 分配一个字符串 message = 14; // 分配一个数字
This dynamic gives us flexibility and simplifies variables statement.
On the downside, we can never be sure that a variable contains a value of a certain type. For example, the following function greet(who)
requires a string parameter, however, we can call the function with any type of parameter:
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!'
Sometimes we need to check the value of a variable in JS Type, what to do?
Use the typeof
operator and instanceof
to check the instance type.
1.<span style="font-size: 18px;">typeof</span>
operator
in JS , the basic types include String
, Number
, Boolean
, and Symbol
, etc. In addition, there are functions, objects, and the special values undefined
and null
.
typeof
is the operator used to determine the type of expression
:
const typeAsString = typeof expression;
expression
evaluates to what we want to find value of type. expression
can be a variable myVariable
, a property accessor myObject.myProp
, a function call myFunction()
or a number 14
.
typeof expression
, depending on the value of expression
, the result may be: 'string'
, 'number'
, 'boolean'
, 'symbol'
, 'undefined'
, 'object'
, 'function'
.
Let’s take a look at each type of typeof
operator:
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
As we can see above, the result of using typeof
to determine the object is 'object'
.
However, typeof null
will also be calculated as 'object'
!
const missingObject = null; typeof missingObject; // => 'object'
typeof null
is 'object'
is a bug in the initial implementation of JS.
Therefore, when using typeof
to detect objects, you need to additionally check null
:
function isObject(object) { return typeof object === 'object' && object !== null; } isObject({ name: 'Batman' }); // => true isObject(15); // => false isObject(null); // => false
1.2 typeof and undefined variables
Although typeof expression
is usually determined by the type of expression
, you can also use typeof
to determine whether a variable is defined.
// notDefinedVar is not defined notDefinedVar; // throws ReferenceError
typeof
has a nice property that when typeof
evaluates the type of an undefined variable, the ReferenceError
error is not raised:
// notDefinedVar is not defined typeof notDefinedVar; // => 'undefined'
VariablenotDefinedVar
is not defined in the current scope. However, typeof notDefinedVar
does not throw a reference error and instead evaluates to 'undefined'
.
We can use typeof
to detect whether a variable is undefined. If typeof myVar === 'undefined'
is true
, then myVar
is not defined.
2. instanceof operator
The usual way to use a JS function is to call it by adding a pair of brackets after its name:
function greet(who) { return `Hello, ${who}!`; } greet('World'); // => 'Hello, World!'
greet('World')
is a regular function call.
JS functions can do much more: they can even construct objects! To have a function construct an object, just use the new
keyword before the regular function call:
function Greeter(who) { this.message = `Hello, ${who}!`; } const worldGreeter = new Greeter('World'); worldGreeter.message; // => 'Hello, World!'
new Greeter('World')
is to create the instance Constructor call of worldGreeter
.
How to check if JS created a specific instance using a specific constructor? Use the instanceof
operator:
const bool = object instanceof Constructor;
where object
is the expression that evaluates the object, and Constructor
is the class or function that constructs the object , instanceof
evaluates to a Boolean value.
worldGreeter
The instance is created using the Greeter
constructor, so this worldGreeter instanceof Greeter
evaluates to true
.
Starting from ES6, you can use class
to define objects. For example, define a class Pet
and then create an instance of it 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');
不出所料,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
更多编程相关知识,请访问:编程课程!!
The above is the detailed content of Type checking in JavaScript: the difference between typeof and instanceof operators. For more information, please follow other related articles on the PHP Chinese website!