In a weakly typed language like Javascript, determining the type of a variable is never that easy. Determining the type of a variable also makes it safer to use it without throwing exceptions.

New operator

The new operator usually applies to constructors, which are just our own names for distinguishing functions. It is essentially a function, so a constructor can be called syntactically like a normal function, but that doesn’t quite serve the purpose of the constructor itself, so we call it a constructor.

The purpose of a constructor is to create an object and set a series of properties on the object. If it must be distinguished from constructors, ordinary functions are more like doing some logical processing on existing objects.

To avoid calling the constructor incorrectly, we can add a detection mechanism as shown in the following code example to avoid potential pitfalls.

The constructor

function Constructor(){
    if(! (this instanceof Contructor)){
        throw "should called by new"
    }
    this.value = 1;
}
Copy the code

The instanceof operator

The instanceof operator detects that an object is an instanceof a constructor, that is, a test

ele.__proto__ === Constructor.prototype

// demo
var a = {};
function C(){}
a.__proto__ = C.prototype;
a instanceof C // true
Copy the code

Extension, JS type detection

There are generally two methods for type checking existing objects

  • typeof
  • Object.prototype.toString.call

The following demo shows the results of both tests for related variable types involved in Javascript, and the differences between the two

// "0", 0, null, undefined, {}, function(){}, [], false var types = ["0", 0, null, undefined, {}, function(){}, [], false]; for(var i=0; i<types.length; i++){ console.log(typeof types[i]); console.log(Object.prototype.toString.call(types[i])); } string [object String] number [object Number] object [object Null] undefined [object Undefined] object [object Object]  function [object Function] object [object Array] boolean [object Boolean]Copy the code

Differential statistics:

type typeof Object.prototype.toString.call
null object [object Null]
{} object [object Object]
[] object [object Array]

Can be seen from the table, the typeof itself unable to distinguish between null, {}, [] the three types, if you need any specific distinction between the three types you need to use the Object. The prototype. ToString. Call method.