InJavaScriptboth 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 functiongreet(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 thetypeof
operator andinstanceof
to check the instance type.
1.typeof
operator
in JS , the basic types includeString
,Number
,Boolean
, andSymbol
, etc. In addition, there are functions, objects, and the special valuesundefined
andnull
.
typeof
is the operator used to determine the type ofexpression
:
const typeAsString = typeof expression;
expression
evaluates to what we want to find value of type.expression
can be a variablemyVariable
, a property accessormyObject.myProp
, a function callmyFunction()
or a number14
.
typeof expression
, depending on the value ofexpression
, the result may be:'string'
,'number'
,'boolean'
,'symbol'
,'undefined'
,'object'
,'function'
.
Let’s take a look at each type oftypeof
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 usingtypeof
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 usingtypeof
to detect objects, you need to additionally checknull
:
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
Althoughtypeof expression
is usually determined by the type ofexpression
, you can also usetypeof
to determine whether a variable is defined.
// notDefinedVar is not defined notDefinedVar; // throws ReferenceError
typeof
has a nice property that whentypeof
evaluates the type of an undefined variable, theReferenceError
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 usetypeof
to detect whether a variable is undefined. Iftypeof myVar === 'undefined'
istrue
, thenmyVar
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 thenew
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 instanceConstructor call of worldGreeter
.
How to check if JS created a specific instance using a specific constructor? Use theinstanceof
operator:
const bool = object instanceof Constructor;
whereobject
is the expression that evaluates the object, andConstructor
is the class or function that constructs the object ,instanceof
evaluates to a Boolean value.
worldGreeter
The instance is created using theGreeter
constructor, sothis worldGreeter instanceof Greeter
evaluates totrue
.
Starting from ES6, you can useclass
to define objects. For example, define a classPet
and then create an instance of itmyPet
:
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!