Seven data types

Basic data types (simple or primitive) : Undefined, Null, Boolean, Number, String Complex data types: Object New data types in ES6: Symbol Objects are the most complex data types and can be divided into three subtypes: Object, array, function (informal)

The typeof operator

	var s = "yicong";
	var b = true;
	var n = null;
	var u;
	var o = new Object(a);function f(){};
	typeof s; // string
	typeof b; // boolean
	typeof n; / / object special
	typeof u; // undefined
	typeof o; // object
	typeof f; // function 
	typeof Symbol(a);// symbol
	typeof {}; // object
	typeof []; // object
	typeof window; // object
	typeof NaN; // number
Copy the code

As we know:

When checking reference types, Typeof returns Object, so typeof is not very useful when checking reference value types, so we use the instanceof operator provided by ECMAScript to check reference type values.

  • The instanceof operator returns true if the value is a reference type;
  • Note that all values of reference types are instances of Object. If you use the instanceof operator to detect values of primitive types, it will return false.

Why are all values of reference types instances of Object?

Because when you write [] on the console, it already implicitly helps you with new Array(), Array() is a constructor, so [] is an instance of the object.

Answer: Because base types are not objects

Hand rip instanceof operator

function instance_of(ordinary,construct){
    let conProto = construct.prototype;
    ordinary = ordinary.__proto__;
    while(true) {// Continue the loop, i.e. search on the prototype chain of Ordinary, until the prototype chain of Ordinary has construct. Prototype
        if(ordinary === null) {return false;
        }	
        if (ordinary === conProto){
            return true; } ordinary = ordinary.__proto__; }}Copy the code

In other words:

  • Is the ordinary object constructed from the construct constructor (new)?
  • Is there a construct prototype on the prototype chain of Ordinary object

Example:

function Fn() {						// constructor

}
var fn = new Fn();                   // Common objects

console.log(fn instanceof Object) 	// Does fn have object.prototype on its prototype chain?
console.log(fn instanceof Function) // Fn has function.prototype on its chain.
console.log(fn instanceof Fn)		// There is no fn. Prototype on the fn chain.
console.log(Fn instanceof Function)	// Fn has function.prototype on its chain.
Copy the code