preface

The following content is self-study and collation, if there are mistakes welcome to point out

– typeof

The typeof operator returns a string representing the typeof the unevaluated operand. Used to determine basic data types

MDN

type The results of
Undefined "undefined"
Null "object"
Boolean "boolean"
Number "number"
BigInt(New in ECMAScript 2020) "bigint"
String "string"
Symbol(New in ECMAScript 2015) "symbol"
Host object (provided by the JS environment) It depends on the implementation
FunctionObject (implemented according to the ECMA-262 specification [[Call]]) "function"
Any other object "object"
/ / values
typeof 37= = ='number';
typeof 3.14= = ='number';
typeof(42) = = ='number';
typeof Math.LN2 === 'number';
typeof Infinity= = ='number';
typeof NaN= = ='number'; // Although it is short for "not-a-number"
typeof Number(1) = = ='number'; // Number attempts to parse the argument to a numeric value

// Bigint
typeof 42n= = ='bigint';

// All current browsers expose a non-standard host object of type undefined
typeof document.all === 'undefined';

/ / string
typeof ' '= = ='string';
typeof '1'= = ='string'; // Note that a numeric string is still a string
typeof (typeof 1) = = ='string'; // Typeof always returns a string
typeof String(1) = = ='string'; // String converts any value to a String, which is safer than toString

/ / a Boolean value
typeof true= = ='boolean';
typeof false= = ='boolean';
typeof Boolean(1) = = ='boolean'; // Boolean() converts based on whether the argument is true or imaginary
typeof!!!!! (1) = = ='boolean'; // Two calls! The (logical non) operator is equivalent to Boolean()

// Symbols
typeof Symbol() = = ='symbol';
typeof Symbol('foo') = = ='symbol';
typeof Symbol.iterator === 'symbol';

// Undefined
typeof undefined= = ='undefined';
typeof declaredButUndefinedVariable === 'undefined';
typeof undeclaredVariable === 'undefined';

/ / object
typeof {a: 1} = = ='object';

// Distinguish between arrays and ordinary objects
typeof [1.2.4= = ='object';
typeof new Date() = = ='object';
typeof /regex/ === 'object'; 

// The following example is confusing, dangerous and useless. Avoid them.
typeof new Boolean(true) = = ='object';
typeof new Number(1) = = ='object';
typeof new String('abc') = = ='object';

/ / function
typeof function() = = = {}'function';
typeof class C = = = {}'function'
typeof Math.sin === 'function';

// null
typeof null= = ='object'; // This has been true since the birth of JavaScript. In the original implementation of JavaScript, values in JavaScript were represented by a tag representing a type and actual data values. The type label of the object is 0. Because 'null' represents a null pointer (the value is 0x00 on most platforms), null's type label is 0 and 'typeof NULL' therefore returns' object '

** * Before ECMAScript2015, Typeof was always guaranteed to return a string for any given operand. * Typeof can return 'undefined' even if there is no declared identifier. Using Typeof never throws an error. * However, after adding a block-scoped [let], using * typeof on let and const variables in the block before they are declared raises a ReferenceError that the block-scoped variable will be in a "dead zone" at the head of the block until it is initialized, during which time, Accessing a variable will raise an error. * /
typeof undeclaredVariable === 'undefined';
typeof newLetVariable; // ReferenceError
typeof newConstVariable; // ReferenceError
typeof newClass; // ReferenceError

let newLetVariable;
const newConstVariable = 'hello';
class newClass{};
Copy the code

– instanceof

The instanceof operator is used to test whether constructor. Prototype exists on the prototype chain of the parameter Object.


/** * It is important to note that if the expression obj instanceof Foo returns true, it does not mean that the expression will always return true. It is possible that the changed value does not exist in the prototype chain of obj, and the value of the original expression will become false. In another case, the value of the original expression can also change, in the case of changing the prototype chain of the object obj. * Although in the current ES specification, we can only read the object's prototype and not change it, this is possible with the help of the nonstandard __proto__ pseudo-attribute. For example, obj.__proto__ = {}, obj instanceof Foo will return false. * /
// Define the constructor
function C(){}
function D(){}

var o = new C();

o instanceof C; // true because object.getProtoTypeof (o) === c.protoType

o instanceof D; // false, because d.prototype is not on o's prototype chain

o instanceof Object; / / true, because the Object. The prototype. IsPrototypeOf (o) returns true
C.prototype instanceof Object // true

C.prototype = {};
var o2 = new C();

o2 instanceof C; // true

o instanceof C; // false, c. protoType refers to an empty object that is not on o's prototype chain.

D.prototype = new C(); / / inheritance
var o3 = new D();
o3 instanceof D; // true
o3 instanceof C; // true because c. prototype is now on the prototype chain for O3
Copy the code

Handwriting implementation instanceof


/ * * * *@param {*} Obj instance object *@param {*} Func constructor *@return true / false
 */
 const myInstanceOf = (obj, func) = > {
    if (obj === null || typeofobj ! = ='object') {
      return false
    }
    
    let proto = Object.getPrototypeOf(obj)
    
    if (proto === func.prototype) {
      return true
    } 
    if (proto === null) {
      return false
    } 
    return myInstanceOf(proto, func)
  }
  
  / / test
  let Fn = function () {}let instance = new Fn()
  
  console.log(myInstanceOf({}, Object)) // true
  console.log(myInstanceOf(instance, Fn)) // true
  console.log(myInstanceOf({}, Fn)) // false
  console.log(myInstanceOf(null, Fn)) // false
  
Copy the code

– Object.prototype.toString()

The toString() method returns a string representing the object.

/** * The type of each object can be obtained by toString(). To every Object through the Object. The prototype. The toString () to test, * need to Function in the prototype. The call () or the Function. The prototype, the apply () in the form of a call, * Pass the object to be checked as the first argument, called thisArg. * /
let toString = Object.prototype.toString;

toString.call(new Date); // [object Date]
toString.call(new String); // [object String]
toString.call(Math); // [object Math]

/ / Since JavaScript 1.8.5
toString.call(undefined); // [object Undefined]
toString.call(null); // [object Null]
Copy the code

Encapsulate a judgment array or object with toString()

const isType = type= > target= > Object.prototype.toString.call(target) === `[object ${type}] `

const isArray = isType('Array')

const isObject = isType('Object')

/ / test
console.log(isArray([]))  // true
console.log(isObject({})) // true
console.log(isObject(null)) // false
Copy the code