The usage and differences of the instanceof and typeof operators in JavaScript are explained in detail

  • 2020-03-29 23:52:05
  • OfStack

Instanceof and typeof in JavaScript are often used to determine what type (instance) a variable is, but their use is different:

The typeof operator
Returns a string that represents the data type of the expression.

Typeof expression;

The expression parameter is an arbitrary expression that needs to find type information.

instructions
Typeof is a unary operator that comes before an operand.

The typeof operator returns the type information as a string. There are six possible typeof return values: "number", "string", "Boolean", "object", "function", and "undefined."

ECMAScript has five primitive types: Undefined, Null, Boolean, Number, and String.

Note:

1. We mentioned the five primitive types of ECMAScript above. When using the typeof operator, we need to distinguish between "object type" and "object value "(literal). For example, a Boolean object is a reference type of a Boolean primitive type, while true and false are two possible object values of a Boolean object. We can think of ECMAScript's predefined objects (as opposed to classes in other languages) as wrappers (or wrappers) of primitive values of the corresponding type. All of ECMAScript's predefined objects are inherited from Object objects. Therefore, the following situation exists:


  var testvar= new Number(68);
  alert(typeof testvar);  //The output   "Object"
  testvar= 68;
  alert(typeof testvar);  //The output   "Number"

Such as:

  function Person(){}
  document.write ("<br>typeof(Person):"+typeof(Person));    //function
  var person = new Person();
  document.write ("<br>typeof(person):"+typeof(person));    //object

Note: Traditionally, ECMAScript does not really have classes. In fact, the word "class" does not appear in ecma-262 at all, except to say that there are no classes. ECMAScript defines "object definitions," which are logically equivalent to classes in other programming languages.

Also: these predefined objects override the ValueOf() method of the Object Object, returning its original value. All the properties and methods of these objects can be applied to the original values of the corresponding types because they are pseudo-objects.

2. The typeof operator returns "Object" for null values. This was actually an error in the original implementation of JavaScript that was then followed by ECMAScript. Now null is considered a placeholder for an object, thus explaining this contradiction, but technically it is still the original value.

Tip:

1. The value undefined is not the same as an undefined value. However, the typeof operator does not really distinguish between the two values. Consider the following code:

Var oTemp;
Alert (typeof oTemp);   / / output "undefined"
Alert (typeof oTemp2);   / / output "undefined"

The previous code outputs "undefined" for both variables, even though only the variable oTemp2 has never been declared. Using an operator other than typeof for oTemp2 causes an error because the other operators can only be used on declared variables.

2. When the function has no explicit return value, the return value is also "undefined", as shown below:

The function testFunc () {}
Alert (testFunc () = = undefined);   // output "true"3, type Null, it has a special value of Null, that is, its literal. The value undefined is actually derived from the value null, so ECMAScript defines them as equal.

Alert (null = = undefined);   / / output "true"
Although these two values are equal, they have different meanings:

Undefined is the value of a variable that is declared but not initialized, or an undeclared variable (it can only be used for typeof, but the compiler automatically declares it as a global variable when it is the target of an assignment).

Null is used to represent an object that does not already exist (that is, the object is empty, or the object cannot be found). If the function or method is returning an object, it usually returns null when the object is not found.

3. We can use typeof to get whether a variable exists, such as if(typeof a! ="undefined"){alert("ok")}, instead of using if(a) because if a does not exist (undeclared), an error occurs.


The instanceof operator
There is a problem with using the typeof operator to store values in reference types, which return "object" regardless of the typeof object being referenced. ECMAScript introduces another Java operator, instanceof, to solve this problem.

The instanceof operator is similar to the typeof operator and is used to identify the typeof object being processed. Unlike the typeof method, the instanceof method requires the developer to explicitly confirm that the object is of a particular type. Such as:

Var oStringObject = new String("hello world");
Alert (oStringObject instanceof String);   / / output "true"
This code asks "is the variable oStringObject an instance of a String object?" OStringObject is indeed an instance of a String object, so the result is "true". Although not as flexible as the typeof method, the instanceof method is useful in cases where the typeof method returns "object".

The instanceof operator

Is a binary operator. Returns a Boolean value indicating whether the object is an instance of a particular class.

Expression  Instanceof class

parameter

  Expression  Will be options. Any object expression.

  Class required. Any defined object class.

instructions
The instanceof operator returns true if object is an instanceof class. Returns false if object is not an instance of the specified class, or if object is null.

To determine whether a variable is an instance of an object,

Var a = new Array (); Alert (a instanceof Array); The alert(an instanceof Object) returns true; This is because Array is a subclass of object.

Function test(){}; Var a = new test (); Alert (an instanceof test) returns true.

Note:

On arguments for function, we might all agree that arguments are an Array, but if you test them with instaceof, you'll find that arguments are not an Array object, although they look similar.

There are also similar situations, such as:

Var a = new Array (); If (an instanceof Object) alert('Y'); The else alert (" N "); Have to 'Y'

But if (window instanceof Object) alert('Y'); The else alert (" N "); Have to 'N'

Therefore, the object of instanceof test here refers to the object in js syntax, not to the dom model object.

Using typeof makes a difference: alert(typeof(window)) yields object

By extension: what is the principle of the instanceof operator in JavaScript?

When learning js, you can use the instanceof operator, such as function Person(){}, to determine whether an instanceof js belongs to a certain type.

Var person = new person ();   Alert (person instanceof person); / / return true

So what was the judgment that the instanceof operation returned true/false?

Could it be that the results are based on whether the references to person.prototype and the internal pointer to Person [[prototype]] are the same?

In fact, true is returned for any prototype object to which the constructor's prototype property points in the instance's prototype object chain.

Prototype is not a property of the instance at all (or the instance's prototype property is undefined), but a property of its prototype object, which cannot be returned correctly if tampered with.

Also, can you directly determine person-constructor == person to get the desired result?

Let's do a test with the following JavaScript code:


function Person(name,sex){this.name=name;this.sex=sex;}
document.write ("<br>typeof Person:"+typeof Person);
document.write ("<br>typeof Person.prototype:"+typeof Person.prototype);
document.write ("<br>typeof Person.constructor:"+typeof Person.constructor);
var person = new Person();
document.write ("<br><br>var person = new Person();");
document.write ("<br>typeof person:"+typeof person);
document.write ("<br>typeof person.prototype:"+typeof person.prototype);
document.write ("<br>typeof person.constructor:"+typeof person.constructor);
document.write ("<br><br>Function.constructor:"+Function.constructor);
document.write ("<br><br>Function.prototype:"+Function.prototype);
document.write ("<br><br>Person.constructor:"+Person.constructor);
document.write ("<br><br>Person.prototype:"+Person.prototype);

document.write ("<br><br>person.constructor:"+person.constructor);
document.write ("<br><br>person.prototype:"+person.prototype);

The output is as follows:

Typeof Person: the function
Typeof Person. The prototype: object
Typeof Person. Constructor: the function

Var person = new person ();
Typeof person: object
Typeof person. The prototype: undefined
Typeof person. Constructor: the function


Function. The constructor: the Function the Function () {} [native code]
The Function prototype: the Function of Empty () {}

Person. The constructor: the function the function () {} [native code]
Person. The prototype: [object object]

Person. The constructor: the function of the person (name, sex) {enclosing name = name; This. Sex = sex; }
Person. The prototype: undefined

Like Function, Number() is the constructor of the Number object, and Number() is used to convert its arguments to the numeric Number type and return the result of the conversion (NaN if not converted).

Rarely used in JavaScript for constructors, a variable-constructor returns a string representation of the constructor of its object class.

So when determining the data type in JavaScript, we can use the following methods to get the detailed data type:

If (typeof (a = = "object") && (a.c onstructor = = Array)) {
...
}

Note: Constructors can only judge existing variables, while typeof can judge undeclared variables or empty objects (return undefined).


Related articles: