A deep understanding of typeof and instanceof javascript
This time I will talk about the usage and attention of the javascript type judgment function typeof and the constructor prototype instanceof.
Typeof
Let's talk about it first.TypeofRight. Note that the typeof MethodReturns a string., To indicateData Type.
Syntax explanation
Let's take a look at the typeof values corresponding to each data type:
Data Type |
Type |
Undefined |
"Undefined" |
Null |
"Object" |
Boolean Value |
"Boolean" |
Value |
"Number" |
String |
"String" |
Symbol (ECMAScript 6 added) |
"Symbol" |
Host Object (provided by the JS environment, such as a browser) |
Implementation-dependent |
Function object |
"Function" |
Any other object |
"Object" |
Let's take a look at the specific instance:
// Numberstypeof 37 === 'number'; typeof 3.14 === 'number'; typeof Math. LN2 = 'number'; typeof Infinity = 'number'; typeof NaN = 'number '; // although NaN is short for "Not-A-Number", it means "Not A Number" typeof number (1) = 'number'; // do Not use it like this! // Stringstypeof "" = 'string'; typeof "bla" = 'string'; typeof (typeof 1) = 'string '; // typeof returns a String typeof string ("abc") ==== 'string'; // do not use it like this! // Booleanstypeof true = 'boolean'; typeof false = 'boolean'; typeof boolean (true) = 'boolean'; // do not use it like this! // Symbolstypeof Symbol () === 'symbol'; typeof symbol ('foo') === 'symbol'; typeof Symbol. iterator = 'symbol'; // Undefinedtypeof undefined = 'undefined'; typeof blabla = 'undefined'; // an undefined variable, or a variable that defines but does not assign an initial value // Objectstypeof {a: 1 }== 'object'; // use Array. isArray or Object. prototype. toString. the call method can be divided from basic objects into array types: typeof [1, 2, 4] === 'object'; typeof new Date () === 'object '; // The following is confusing. Do not use it like this! Typeof new Boolean (true) === 'object'; typeof new Number (1) === 'object'; typeof new String ("abc ") === 'object'; // function typeof function () {}== 'function'; typeof Math. sin = 'function ';
We will find that typeof is not accurate in determining the data type. For example, arrays, regular expressions, dates, and object typeof return values are all objects, which may cause some errors.
Therefore, based on the typeof judgment type, we still need to useObject. prototype. toStringMethod to further determine the data type.
Let's take a look at the difference between the toString method and the typeof method return value in the case of the same data type:
Data |
ToString |
Typeof |
"Foo" |
String |
String |
New String ("foo ") |
String |
Object |
New Number (1.2) |
Number |
Object |
True |
Boolean |
Boolean |
New Boolean (true) |
Boolean |
Object |
New Date () |
Date |
Object |
New Error () |
Error |
Object |
New Array (1, 2, 3) |
Array |
Object |
/Abc/g |
RegExp |
Object |
New RegExp ("meow ") |
RegExp |
Object |
We can see that the toString method can correctly distinguish Array, Error, RegExp, Date, and other types.
Therefore, we generally use this method to verify the data type.
True question Detection
However, since typeof is mentioned today, I will list several questions to see if I have mastered the usage of typeof.
Question 1:
var y = 1, x = y = typeof x; x;
Question 2:
(function f(f){ return typeof f(); })(function(){ return 1; });
Question 3:
var foo = { bar: function() { return this.baz; }, baz: 1 }; (function(){ return typeof arguments[0](); })(foo.bar);
Question 4:
var foo = { bar: function(){ return this.baz; }, baz: 1 } typeof (f = foo.bar)();
Question 5:
var f = (function f(){ return "1"; }, function g(){ return 2; })();typeof f;
Question 6:
var x = 1; if (function f(){}) { x += typeof f; } x;
Question 7:
(function(foo){ return typeof foo.bar; })({ foo: { bar: 1 } });
The answer to these seven questions is as follows:
"undefined","number","undefined","undefined","number","1undefined","undefined"
How many operations have you done? Is it very confusing? Although all of these questions have typeof, I have investigated a lot of javascript basics. Next, let's take a closer look.
Question 1:
var y = 1, x = y = typeof x; x;//"undefined"
The expression is from right to left.Variable increaseThe type is not null, but undefined, so x = y = "undefined ".
Variable upgrade I mentioned in this Article. Let's take a look.
Question 2:
(function f(f){ return typeof f();//"number" })(function(){ return 1; });
The input parameter is f, that is, function () {return 1. After f () is executed, result 1 is obtained. Therefore, typeof 1 returns "number ". This question is very simple, mainly to distinguish between f and f ().
Question 3:
var foo = { bar: function() { return this.baz; }, baz: 1 }; (function(){ return typeof arguments[0]();//"undefined" })(foo.bar);
This question examines the point of this.This always points to the context when the function is executed, rather than(The Arrow function of ES6 is not counted ). When arguments is executed, this already points to the window object. So it is "undefined ". If you are not familiar with this execution, you can read this article: For more information about this, if you are interested in the arrow function you just mentioned, you can take a look at the arrow function of ES6.
Question 4:
var foo = { bar: function(){ return this.baz; }, baz: 1 } typeof (f = foo.bar)();//undefined
If the above question is correct, this question should not be wrong. It is also the point of this.
Question 5:
var f = (function f(){ return "1"; }, function g(){ return 2; })();typeof f;//"number"
This question is easy to make wrong, because I have never encountered javascript before this question.Group Selector. What is a group selector? The following is an example:
Var a = (, 3); document. write (a); // 3, the last one prevails
So the above question will return 2, typeof 2 of course is "number.
Question 6:
var x = 1; if (function f(){}) { x += typeof f; } x;//"1undefined"
This is a javascript language specification problem. Add a function declaration to the condition judgment. If this statement is correct, true is returned, but the javascript engine cannot find this function during search. Therefore, the result is "1undefined ".
Question 7:
(function(foo){ return typeof foo.bar; })({ foo: { bar: 1 } });
This question is actually a matter of detail. The foo parameter points to the whole {foo: {bar: 1. Believe this and you will understand it.
Okay. The above questions are all good resources.
Instanceof
Next, let's talk about the instanceof method. The instanceof operator can be used to determine the prototype attribute of a constructor.Whether it exists in anotherObject To Be DetectedOn the prototype chain.
If you are not familiar with the prototype, you can take a look at the prototype.
Let's take a look at the instanceof instance:
// Define the constructor function C () {} function D () {} var o = new C (); // true, because Object. getPrototypeOf (o) = C. prototypeo instanceof C; // false, because D. prototype is not in the o prototype chain. o instanceof D; o instanceof Object; // true, because Object. prototype. isPrototypeOf (o) returns trueC. prototype instanceof Object // true, same as C. prototype = {}; var o2 = new C (); o2 instanceof C; // trueo instanceof C; // false, C. prototype points to an empty object, which is not in the prototype chain of o. d. prototype = new C (); // inherit var o3 = new D (); o3 instanceof D; // trueo3 instanceof C; // true
But here we need to pay attention to one problem:
function f(){ return f; }document.write(new f() instanceof f);//falsefunction g(){}document.write(new g() instanceof g);//true
First, why is false returned? Because the prototype of the constructor is overwritten, let's look at the difference between new f and new g: