This article has participated in the activity of “New person creation Ceremony”, and started the road of digging gold creation together.

The basic method of judgment

1. Typeof (not allowed)

The typeof operator is usually the first thing that comes to mind because Typeof is specifically used for type detection, but Typeof does not meet such requirements, such as

Let a = [' 7 ', '4', '1']. The console log (typeof (a)) / / output objectCopy the code

2. instanceof

The instanceof operator is used to check whether a variable is an instanceof a type of data by looking up the prototype chain. The instanceof operator can be used to determine whether a variable is an array or an object.

var a = [1, 2, 3]; console.log(a instanceof Array); // true console.log(a instanceof Object); Var userInfo = {userName: "zhangsan"}; console.log(userInfo instanceof Array); // false console.log(userInfo instanceof Object); // true //userInfo is just an object, not an arrayCopy the code

Based on the above logic, we can encapsulate the following functions to determine whether a variable is an array type or an object type

Var a = [1,2,3] function getType(obj){if(obj instanceof Array){returen 'Array' }else if(obj instanceof Object){return 'Object'}else{return 'neither Array nor Object'}} console.log(getType(a))Copy the code

In a recent interview, the interviewer asked, what is the underlying principle of Instanceof? Let's dig a little deeper into how Instanceof works

2.1 How instanceof Low-level works:

Instanceof is described in MDN as follows:

The instanceof operator tests whether the constructor’s Prototype property appears anywhere in the object’s prototype chain

In other words, if A is instanceof B, then A must be an object and B must be A legitimate JavaScript function. When both conditions are met:

Check whether B’s prototype property points to A prototype object (B. protoType) that is on the prototype chain of object A.

If yes, true; If not, false.

Function instance_of(L, R) {var O = r.protoType; // take the display prototype of R L = l.__proto__; While (true) {if (L === null) return false; If (O === L) // Return true if O explicit archetype is exactly equal to L implicit archetype; L = L.__proto__; }}Copy the code

2.2 How does Instanceof judge by cutting off the pointing of the original prototype and pointing to a new object through prototype inheritance?

No inheritance has occurred

function Person(name,age,sex){ this.name = name; this.age = age; this.sex = sex; } function Student(score){ this.score = score; } var per = new Person(20, 20); Var stu = new Student (98) console.log(per instanceof Person); // true console.log(stu instanceof Student); // true console.log(per instanceof Object); // true console.log(stu instanceof Object); // trueCopy the code

A prototype diagram where no inheritance relationship has occurred

There is an inheritance

function Person(name,age,sex){ this.name = name; this.age = age; this.sex = sex; } function Student(name,age,sex,score){ Person.call(this,name,age,sex); this.score = score; } Student.prototype = new Person(); Var stu = new Student("小 小 ",20,"男",99); // Create the Student object stu console.log(stu instanceof Student); // true console.log(stu instanceof Person); // true console.log(stu instanceof Object); // trueCopy the code

Prototype diagram after inheritance

Workflow analysis of Instanceof after inheritance:

Let’s start with Stu Instanceof Student
Function instance_of(L, R) {//L = stu; R = Student var O = r.prototype; //O for student. prototype, now pointing to per L = l.__proto__; // execute loop if (L === null) // do not return false; // execute loop if (L === null); If (O === L) // Judge: Student. Prototype ===stu._proto_? return true; // In this case, both parties refer to the instance object per of Person, so true L = L.__proto__; }}Copy the code

Therefore, stu instanceof Student is still valid even if archetypal inheritance occurs.

Stu instanceof Person. How does Instanceof judge that STU inherits Person
Function instance_of(L, R) {// L = stu; Person var O = r.prototype; Prototype L =.__proto__; While (true) {// execute the loop if (L === null) // do not return false; If (O === L) // Judge: Person. Prototype === stu._proto_? return true; // At this point, stu._proto_ refers to the per instance object, which does not satisfy L = L.__proto__; / / make L = stu. _proto_. _proto_, execute cycle} / / stu _proto_. _proto_, see here:} / / is refers to the Person. The prototype, so return trueCopy the code

2.3 the conclusion

1. The role of Instanceof

Used to determine whether a reference type belongs to a constructor;

It can also be used in inheritance relationships to determine whether an instance belongs to its parent type.

2, and typeof differences:

Typeof specifies the value types number, string, object, Boolean, function, undefined, and symbol. However, objects {}, arrays [], and NULL all return object. To compensate for this, Instanceof determines which constructor a reference belongs to, and thus its data type, from a prototypical perspective.

3. Check by constructor

Determining whether a variable is an Array or an Object is essentially determining whether the variable’s constructor is of type Array or Object. Because an instance of an object is created through a constructor. Because an instance of an object is created through a constructor.

 var a = [1, 2, 3];
      console.log(a.__proto__.constructor === Array); //true
      console.log(a.__proto__.constructor === Object); // false
Copy the code

And likewise here, here we can encapsulate a function to determine whether a variable is an array type or an object type.

Constructor = o.__proto__. Constructor; if (constructor === Array) { return "Array"; } else if (constructor === Object) { return "Object"; } else {return "Parameter type is neither Array nor Object"; } } var a = [1, 2, 3]; console.log(getType(a));Copy the code

4. Check by the toString() function

Each reference type inherits the Object type directly or indirectly, so they all contain the toString() function. The toString() function returns different values for different data types, so we can use toString() to determine whether a variable is an array or an Object. Of course, we need to use the call method to call the toString() function on the Object prototype to determine the type.

var arr = [1, 2, 3]; var obj = { userName: "zhangsan" }; console.log(Object.prototype.toString.call(arr)); //[object Array] console.log(Object.prototype.toString.call(obj)); // [object Object] console.log(arr.toString()); / / 1, 2, 3Copy the code

5. Check by using the array. isArray() function

The array. isArray method is used to determine whether a variable is an Array. When detecting Array instances, array. isArray is superior to instanceof because array. isArray can detect iframes.

    var arr = [1, 2, 3];
      var obj = { name: "zhangsan" };
      console.log(Array.isArray(1)); //false
      console.log(Array.isArray(arr)); //true
      console.log(Array.isArray(obj)); //false
Copy the code

The above content is for learning reference only, if there is an error welcome to point out