The first thing you should know is what is typeof?

Typeof is a unary operation that precedes an operand, which can be of any type. The return value is a string that specifies the type of operand. Typeof can be used to detect the data typeof a given variable.

What is instanceof?

The nstanceof operator is used to determine whether the object pointed to by the constructor’s prototype property is on the prototype chain of another object to be tested. In general, using instanceof is to determine whether an instance belongs to a certain type.

Similarities between typeof and Instanceof in JS:

Typeof and instanceof are commonly used in JavaScript to determine whether a variable is empty or of what type.

Differences:

Definition and usage of typeof

The return value is a string that specifies the data type of the variable.

Usage details:

Typeof usually returns only the following results:

‘undefined’ : This value is undefined.

‘Boolean’ : This value is a Boolean.

‘String’ : This value is a string.

‘number’ : This value is a numerical value.

‘Object’ : This value is an object or NULL.

‘function’ : This value is a function. Typeof to get whether a variable exists, as in

if(typeof a! =”undefined”){alert(“ok”)}

Do not use if(a) because if a does not exist (undeclared) you will get an error.

3. For special objects such as Array and Null, typeof returns object. This is the limitation of Typeof.

Definition and Usage of Instanceof

Definition and usage of Instanceof: Instanceof is used to determine whether a variable belongs to an Instanceof an object. It can also be used to determine whether the prototype property of a constructor exists in the prototype chain of the specified object.

IsPrototypeOf is used to check if the object calling this method exists in the prototype chain of the specified object, so it is essentially checking for different targets.


a instanceof b? alert("true"):alert("false"); // A is an instance of B? True, falseCopy the code

var a=new Array(); alert(a instanceof Array);Copy the code

alert(a instanceof Object)Copy the code


Also returns true;

This is because Array is a subclass of Object.

Such as:

function test() {}; var a=newtest(a); alert(a instanceoftest)Copy the code

Test: Returns object.

var a=new Array();if (a instanceof Object) alert('Y');else alert('N');
if (window instanceof Object) alert('Y');else alert('N');Copy the code

‘Y’, but

‘N’.

So, here the instanceof test object refers to the JS syntax object, not dom model object.

There are some differences using Typeof:

alert(typeof(window))Copy the code

Get the object.