I believe that many partners are just getting started when js, will encounter typeof and instanceof on the usage of a few puzzles, today small and everyone would chat with their respective usage as well as some differences,
You do not worry, we are following on to explain:
js is a weak language, it does not need to determine the variables when you declare a variable type, js at runtime will automatically determine.
typeof
Is used to detect the type of a variable , a return value is a string .
Use : typeof (expression) and typeof variable name
Operator Return value : String, there are seven possible: "undefined", "number" , "string", "boolean", "object", "function", "symbol"
typeof undefined // "undefined"
typeof 1 // "number"
typeof "1" // "string"
typeof false // "boolean"
typeof {} // "object"
typeof [] // "object"
typeof null // "object"
typeof function () {} // "function"
typeof Symbol(1) // "symbol"
(Note: objects, arrays, null return values of typeof are "object")
If we want to determine whether a variable is an array type, recommended: Array.isArray ([]) // to true judge
instanceof
For detecting existence of an object in its constructor a prototype chain prototype property .
Syntax : [Object] the instanceof [constructor]
(Note: the left must be an object, and if not, return directly false)
let num = 1 num instanceof Number // false num = new Number(1) num instanceof Number // true
See here, one might ask, are obviously num and are 1, the result is different Why return it?
In fact, the first is not the object, but the basic type, while the second is encapsulated into an object, it is true. Similarly:
var a = new Array(); console.log(a instanceof Array); // true console.log(a instanceof Object); // true -----------因为 Array 是 Object 的子类
function test(){}; var a = new test(); console.log(a instanceof test) // true
Further, instanceof inheritance may be used in one example determines whether the type of its parent. Such as:
the Fn function () {}; function Foo () {}; Foo.prototype the Fn = new new (); var foo = new new Foo (); the console.log (the instanceof Foo foo); // to true the console.log (foo the instanceof the Fn ); // to true Foo.prototype = {}; var = foo2 new new foo (); the console.log (foo2 the instanceof foo); // to true the console.log (the instanceof foo foo); // to false ------ --- Foo.prototype points to an empty object, this object is not empty foo prototype chain.