Instanceof and typeof in JavaScript are often used to determine what type (instance) a variable is, but there are still differences in their use:
typeof operator
Returns a string that represents the data type of the expression.
typeof expression ;
The expression parameter is any expression that needs to look for type information.
illustrate
typeof is a unary operator before an arithmetic number.
The typeof operator returns the type information as a string. There are six possibilities for typeof return value: "number", "string", "boolean", "object", "function", and "undefined."
(And ECMAScript has 5 primitive types, namely Undefined, Null, Boolean, Number, and String.)
Notes:
1. We mentioned the 5 primitive types of ECMAScript above. When using the typeof operator, we need to specifically distinguish the difference between "object type" and "object value" (literal value). For example, the Boolean object is a reference type of the Boolean primitive type, while true and false are the two possible object values of the Boolean object. We can think of ECMAScript's predefined objects (relative 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 situations exist:
var testvar= new Number(68);
alert(typeof testvar);//Output "object"
testvar= 68;
alert(typeof testvar);//Output "number"
Another example:
function Person(){}
("<br>typeof(Person):"+typeof(Person));//function
var person = new Person();
("<br>typeof(person):"+typeof(person));//object
Notice:In the traditional sense, ECMAScript does not really have classes. In fact, except to indicate that there is no class, the word "class" appears at all in ECMA-262. ECMAScript defines "object definition", which is logically equivalent to classes in other programming languages.
Also: These predefined objects override the ValueOf() method of the Object object, returning its original value. And all properties and methods of these objects can be applied to the original values of the corresponding type because they are pseudo-objects.
2. The typeof operator will return "Object" to the null value. This is actually a bug in the initial implementation of JavaScript, which was then used by ECMAScript. Now, null is considered a placeholder for the object, thus explaining this contradiction, but technically it is still the original value.
hint:
1. The value undefined is different from 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" to both variables, even if only the variable oTemp2 has never been declared. If you use other operators other than typeof for oTemp2, it will cause an error, because other operators can only be used on declared variables.
2. When the function does not have a clear return value, the returned value is also "undefined", as shown below:
function testFunc() {}
alert(testFunc() == undefined); //Output "true"3. Type Null, it has only one dedicated value 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 a value or undeclared variable that declares a variable but is not assigned to it when it is initialized (can only be used for typeof, but the compiler will automatically declare it as a global variable when it is an assignment target).
null is used to represent an object that does not exist yet (i.e. the object is empty, or the object cannot be found). If the function or method wants to return an object, then when the object is not found, it is usually returned null.
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 (not declared), an error will occur.
For special objects such as Array, Null, etc., you will always return object when using typeof. This is exactly the limitation of typeof. If we want to get whether an object is an array, or determine whether a variable is an instance of an object, we need to choose to use instanceof.
instanceof operator
There is a problem when using the typeof operator to store values using the reference type, which returns "object" regardless of the type of 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 type of the object being processed. Unlike the typeof method, 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"
This code asks "Is the variable oStringObject an instance of the String object?" oStringObject is indeed an instance of the 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 binary operator. Returns a Boolean value indicating whether the object is an instance of a specific class.
expression instanceof class
parameter
expression Required option. Any object expression.
Class Required Options. Any defined object class.
illustrate
If object is an instance of class, the instanceof operator returns true . If object is not an instance of the specified class, or object is null, false is returned.
An instance used to determine whether a variable is an object.
For example, var a=new Array();alert(a instanceof Array); will return true, and alert(a instanceof Object) will also return true; this is because Array is a subclass of object.
For example: function test(){};var a=new test();alert(a instanceof test) will return true.
Notice:
Regarding the arguments of function, we may all think that arguments are an Array, but if you use instanceof to test, you will find that arguments are not an Array object, although they look very similar.
There are also 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'
Therefore, the object of the instanceof test here refers to the object in the js syntax, not the dom model object.
And using typeof at this time will have some differences: alert(typeof(window)) will get object
Extended: What is the principle of the instanceof operator in JavaScript?
When learning js, you can use the instanceof operator when judging whether an instance in js belongs to a certain type, such as function Person(){}
var person = new Person(); alert(person instanceof Person);//Return true
So what kind of judgment is passed when executing the instanceof operation, and returns true/false?
Could it be obtained by judging whether the references to the person's internal pointer [[prototype]] are the same?
In fact, if you can find the prototype object pointed to by the prototype attribute of the constructor in the "prototype object chain" of the instance, it will return true.
Prototype is not an attribute that an instance has (or the instance's prototype attribute is undefined), but an attribute in its prototype object. If it is tampered with, this judgment method cannot be returned correctly.
In addition, can we directly judge == Person to achieve the desired result?
Let's do a test, as follows:
function Person(name,sex){=name;=sex;}
("<br>typeof Person:"+typeof Person);
("<br>typeof :"+typeof );
("<br>typeof :"+typeof );
var person = new Person();
("<br><br>var person = new Person();");
("<br>typeof person:"+typeof person);
("<br>typeof :"+typeof );
("<br>typeof :"+typeof );
("<br><br>:"+);
("<br><br>:"+);
("<br><br>:"+);
("<br><br>:"+);
("<br><br>:"+);
("<br><br>:"+);
The output is as follows:
typeof Person:function
typeof :object
typeof :function
var person = new Person();
typeof person:object
typeof :undefined
typeof :function
:function Function() { [native code] }
:function Empty() {}
:function Function() { [native code] }
:[object Object]
:function Person(name,sex){=name;=sex;}
:undefined
Similar to Function, Number() is the constructor of the Number object. Number() is used to convert its parameters to a number type and return the conversion result (if it cannot be converted, it returns NaN).
In JavaScript, constructors are rarely used, returning string representations of the constructors of their object class.
Then when judging data types in JavaScript, we can use the following method to get its detailed data types:
if((typeof a=="object") && (==Array)){
…
}
Notice:The constructor can only judge existing variables, while the typeof can judge undeclared variables or empty objects (return undefined).