Home > Web Front-end > JS Tutorial > body text

Type checking in JavaScript: the difference between typeof and instanceof operators

青灯夜游
Release: 2020-12-17 09:35:13
forward
2290 people have browsed it

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.

Type checking in JavaScript: the difference between typeof and instanceof operators

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; // 分配一个数字
Copy after login

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!'
Copy after login

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;
Copy after login

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'
Copy after login

B) Number:

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

typeof NaN;    // => 'number'
Copy after login

C) Boolean:

const ok = true;
typeof ok; // => 'boolean'
Copy after login

D) Symbol:

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

E) undefined:

const nothing = undefined;
typeof nothing; // => 'undefined'
Copy after login

F) Objects:

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

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

const regExp = /Hi/;
typeof regExp; // => 'object'
Copy after login

G) Functions :

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

typeof greet; // => 'function'
Copy after login

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'
Copy after login

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
Copy after login

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
Copy after login

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'
Copy after login

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!'
Copy after login

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!'
Copy after login

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;
Copy after login

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');
Copy after login

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

由于myPet是使用Pet类构造的-const myPet = new Pet('Lily'), 所以 myPet instanceof Pet 的结果为 true

myPet instanceof Pet; // => true
Copy after login

但是,普通对象不是Pet的实例:

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

我们发现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
Copy after login

2.1 instanceof 和父类

现在,Cat 扩展了父类Pet

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

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

不出所料,myCatCat类的实例:

myCat instanceof Pet; // => true
Copy after login
Copy after login

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

myCat instanceof Pet; // => true
Copy after login
Copy after login

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

原文地址: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!

source:segmentfault.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template