Usage and difference of instanceof and typeof operators in JavaScript detailed parsing _javascript tips

Source: Internet
Author: User
Tags object object type null

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

typeof operator
Returns a string that is used to represent the data type of an expression.

typeof expression;

The expression parameter is any expression that needs to find the type information.

Description
typeof is a unary operator, placed before a shipment count.

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 5 original types (primitive type), that is, Undefined, Null, Boolean, number, and String. )

Comments:

1, we mentioned above ECMAScript 5 original types, when using the TypeOf operator, we need to specifically distinguish between "object type" and "Object Value" (literal) difference. For example, a Boolean object is a reference type of the Boolean original type, and true and false are two possible object values for the Boolean object. We can think of ECMAScript predefined objects (as opposed to classes in other languages) as encapsulation (or wrapper) of the original value of the corresponding type. All predefined objects of ECMAScript are inherited from object objects. Therefore, the following conditions exist:

Copy Code code as follows:

var testvar= new number (68);
Alert (typeof TestVar); Output "Object"
Testvar= 68;
Alert (typeof TestVar); Output "Number"

Another example:
Copy Code code as follows:

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

Note:In the traditional sense, ECMAScript does not really have classes. In fact, in addition to stating that there is no class, the word "class" does not appear in the ECMA-262. ECMAScript defines an "object definition" that is logically equivalent to a class in another programming language.

In addition: These predefined objects overwrite the valueof () method of object objects and return their original values. 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 a null value. This is actually an error in the initial implementation of JavaScript and is then used by ECMAScript. Now, NULL is considered a placeholder for an object, which explains the paradox, but technically it is still the original value.

Tips:

1, value undefined and is different from the undefined value. However, the typeof operator does not really distinguish between these two values. consider the following code:

var otemp;
Alert (typeof otemp); Output "undefined"
Alert (typeof OTEMP2); Output "undefined"

The preceding code outputs "undefined" to two variables, even though only the variable OTEMP2 has never been declared. If you use an operator other than typeof for OTEMP2, it can cause an error because the other operators can only be used on declared variables.

2, when the function does not explicitly return the value, the return is also the value "undefined", as follows:

function TestFunc () {}
Alert (testfunc () = = undefined); Output "true" 3, type NULL, it has only one private value null, that is, its literal amount. Value undefined are actually derived from 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 a value that is given to a variable but not initialized when it is declared, or a variable that is not declared (only for TypeOf, but the compiler automatically declares it as a global variable as an assignment target).

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

3, we can use TypeOf to obtain whether a variable exists, such as if (typeof a!= "undefined") {alert ("OK")}, and not to use if (a) because if a does not exist (not declared) will be an error.

For Array,null and other special objects to use TypeOf all return object, this is the limitations of TypeOf. If we want to get an object to be an array, or to determine whether a variable is an instance of an object, choose to use instanceof.


instanceof operator
Storing a value using a reference type when using the TypeOf operator can cause an issue that returns "Object" regardless of what type of object is referenced. ECMAScript introduced another Java operator instanceof to solve the problem.

The instanceof operator is similar to the typeof operator and is used to identify the type of object being processed. Unlike the typeof approach, the Instanceof method requires the developer to explicitly confirm that the object is a specific type. For example:

var ostringobject = new String ("Hello World");
Alert (ostringobject instanceof String); Output "true"
The 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 when the TypeOf method returns "Object".

instanceof operator

is a two-dollar operator. Returns a Boolean value that indicates whether an object is an instance of a particular class.

Expression instanceof Class

Parameters

expression Required option. An arbitrary object expression.

Class must be selected. Any defined object class.

Description
If object is an instance of class, the instanceof operator returns TRUE. Returns False if object is not an instance of the specified class, or if object is null.

Used to determine whether a variable is an instance of an object,

If the Var a=new array (); alert (a instanceof Array) returns TRUE, and alert (a Instanceof object) returns True, because the Array is a subclass of Object.

Again, the function test () {};var a=new test (), alert (a instanceof test) returns True.

Attention:

As for the arguments of function, we all may think that arguments is an array, but if you use instaceof to test you will find that arguments is not an array object, although it looks like it.

In addition, there are similar situations, such as:

var a=new Array (); if (a instanceof Object) alert (' Y '); else alert (' N '); Get ' Y '

But if (window instanceof Object) alert (' Y '); else alert (' N '); Get ' N '

So, the object of the instanceof test here refers to the object in the JS syntax, not the DOM model object.

There is a difference between using typeof at this point: alert (typeof window) gets object

Extension: What is the principle of the instanceof operator in JavaScript?

When learning JS, you can use the instanceof operator to determine whether an instance in JS is a certain type, such as function person () {}

var person = new person (); Alert (person instanceof person);//return True

So what was the judgment of the execution of Instanceof this operation and returned to True/false?

Is it possible to derive results by judging whether the person.prototype and person's internal pointer [[prototype]] are referenced the same?

In fact, it returns true if the stereotype object pointed to by the prototype property of the constructor can be found in the "prototype object chain" of the instance.

And prototype is not the attribute of the instance (or the prototype attribute of the instance is undefined), but the attribute in its prototype object, and if it is tampered with, the judgment method cannot be returned correctly.

In addition, can you directly judge person.constructor = = person to achieve the desired results?

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

Copy Code code as follows:

function Person (name,sex) {this.name=name;this.sex=sex}
document.write ("<br>typeof person:" +typeof);
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);
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:function
typeof Person.prototype:object
typeof Person.constructor:function

var person = new person ();
typeof Person:object
typeof person.prototype:undefined
typeof Person.constructor:function


Function.constructor:function function () {[native code]}
Function.prototype:function Empty () {}

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

Person.constructor:function person (name,sex) {this.name=name;this.sex=sex;}
person.prototype:undefined

Similar to function, number () is the constructor for the number object, and numbers () is used to convert its arguments to the numeric # type and return the result of the conversion (return Nan if it cannot be converted).

constructor is less used in JavaScript, Variable.constructor returns a string representation of the constructor of its object class.

So when judging data types in JavaScript, we can use the following methods to get their detailed data types:

if ((typeof a== "Object") && (A.constructor==array)) {
...
}

Note:constructor can only judge an existing variable, whereas TypeOf can judge an undeclared variable or an empty object (return to undefined).

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.