Home > Web Front-end > JS Tutorial > JavaScript Topic 6: Type Detection

JavaScript Topic 6: Type Detection

coldplay.xixi
Release: 2021-03-09 09:47:23
forward
2292 people have browsed it

JavaScriptSpecial topic on data type detection

JavaScript Topic 6: Type Detection

##Directory

    1. typeof
  • 2. instanceof
  • 3. constructor
  • 4. What is stringTag?
  • 5. Methods to implement several data detection
  • Write at the end

(free learning recommendation: javascript video tutorial

Preface

In "JavaScript Data Types" we The problem of simple type detection was also mentioned.

As front-end students, we should all know that typeof and instanceof can be used to determine the type of JavaScript data at runtime. So how do they determine it? Will a thousand people write a thousand judgment methods?

This article will discuss how to determine the data type from the general typeof, to the object-specific instanceof, to isNull, isNumber, isString and other methods. Let’s work together~

JavaScript Topic 6: Type Detection

1. typeof

typeof: OperatorReturns a string indicating the type of the uncalculated operand.

We all know that before ES6, JavaScript had six data types, namely:

    Undefined
  1. Null
  2. Boolean
  3. Number
  4. String
  5. Object
#However, when we use typeof to operate on values ​​of these data types, the result returned But there is no one-to-one correspondence, they are:

    Undefined
  1. object – ***
  2. Boolean
  3. Number
  4. String
  5. Object
There are some surprises,

typeof null => 'object' and typeof function(){} => 'function '

So in most cases we can use typeof to detect basic data types. However, after detecting the

Object, we cannot distinguish which kind of Object it is:

typeof [] === 'object'; //truetypeof {} === 'object'; //truetypeof null === 'object'; //true
Copy after login

Summary

When detecting the original type of Js, except

typeof null returns object, everything else is Returns the lowercase letter of the corresponding type name.

2. Instanceof

When we determine the object type, we can use instanceof:

If you are not familiar with prototypes and prototype chains, you may wish to Take a look at this article From prototype to prototype chain

Definition

The instanceof operator is used to detect whether the prototype attribute of the constructor appears in the prototype chain of an instance object superior.

Instance

const arr = [];const obj = {};console.log(arr instanceof Array);   // trueconsole.log(arr instanceof Object);  // trueconsole.log(obj instanceof Array);   // falseconsole.log(obj instanceof Object);  // true
Copy after login
Note that instanceof can match the parent class of the type, so arr instanceof Array and arr instanceof Object are both true, because Object is the parent class of Array .


Objects that satisfy the parent-child class relationship of

class extends and prototype chain rules can be matched:

class

class Base {}class Current extends Base {}const obj = new Current();console.log(obj instanceof Current); // trueconsole.log(obj instanceof Base); // true
Copy after login

Prototype chain

function Foo() {}function Bar() {}Bar.prototype = new Foo();const obj = new Bar();console.log(obj instanceof Bar); // trueconsole.log(obj instanceof Foo); // true
Copy after login
Note that if we modify the prototype chain of obj, the result of instanceof can be changed:


function Other() {}obj.__proto__ = new Other();console.log(obj instanceof Other); // trueconsole.log(obj instanceof Foo); // false
Copy after login

Summary

Instanceof uses the prototype chain to judge. In fact, as long as a prototype of type

Type is on the prototype chain of a object obj, then obj instanceof Type is true, otherwise it is false.

3. Constructor

Sometimes we don’t want to match the parent type, but only want to match the current type, then we can use constructor to judge:

If you are not familiar with prototypes and prototype chains, you may wish to read this article. From prototype to prototype chain

Definition

Return the

Object that creates the instance object Reference to the constructor. Note that the value of this property is a reference to the function itself, not a string containing the function name.

Instance

const arr = [];console.log(arr.constructor === Array); // trueconsole.log(arr.constructor === Object); // false
Copy after login
The constructor of the object will return its type, and when the type is defined, a name read-only attribute will be created with the value being the name of the type.


class Foo {}console.log(Foo.name); // Fooconst foo = new Foo();console.log(foo.constructor === Foo); // trueconsole.log(foo.constructor.name === 'Foo'); // true
Copy after login

Question

    Is constructor.name necessarily correct?
  • Can we modify it?

4. What is stringTag?

4.1 stringTag——type tag
If you have seen the early implementation of some libraries, you will find that

Object.prototype.toString is used to do type judgment way, they will have a string tag of the data type, called stringTag;

4.2 Object.prototype.toString

Definition

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

Every object has a

toString() method. When the object is represented as a text value, by default, the toString() method is used by every Object objects inherit.

如果此方法在自定义对象中未被覆盖,toString() 返回 “[object type]”,其中 type 是对象的类型。以下代码说明了这一点:

实例

比如这是requirejs里面的代码片段。

var ostring = Object.prototype.toString;function isArray(it) {
  return ostring.call(it) === '[object Array]';}
Copy after login

toString时都做了什么?

这里直接将冴羽大大的总结搬了过来:

When the toString method is called, the following steps are taken:

  1. If the this value is undefined, return “[object Undefined]”.
  2. If the this value is null, return “[object Null]”.
  3. Let O be the result of calling ToObject passing the this value as the argument.
  4. Let class be the value of the [[Class]] internal property of O.
  5. Return the String value that is the result of concatenating the three Strings "[object ", class, and “]”.

当 toString 方法被调用的时候,下面的步骤会被执行:

  1. 如果 this 值是 undefined,就返回 [object Undefined]
  2. 如果 this 的值是 null,就返回 [object Null]
  3. 让 O 成为 ToObject(this) 的结果
  4. 让 class 成为 O 的内部属性 [[Class]] 的值
  5. 最后返回由 "[object " 和 class 和 “]” 三个部分组成的字符串

注意

有几点我们需要注意:

  • toString无法区分原始类型及其构造对象;
    • 我们认为Number、Boolean这种类型在被构造器构造出来后的类型应该是对象
    • 但toString都会返回[object number]等原始类型;
  • toString方法是可以自定义的;

JavaScript Topic 6: Type Detection

五、实现几个数据检测的方法

好了看了几款常用的类型判断方法后,我们可不可以实现自己的类型判断工具?就利用上述提到的一个或多个方法。我们自己动手丰衣足食~

5.1 isObject

注意,我们认为null不是一个对象,它就是null~

function isObject(value) {
    const type = typeof value;
    return value != null && (type === 'object' || type === 'function');}
Copy after login
5.2 isNull
function isNull(value) {
    return value === null;}
Copy after login
5.3 isFunction
function isFunction(value) {
    return typeof value === 'function';}
Copy after login
5.4 isArray
var isArray = Array.isArray || function( value ) {
    return type(value) === "array";}
Copy after login
5.5 stringTag
const toString = Object.prototype.toString;function getTag(value) {
    // if (value === null) return '[object Null]';
    // if (value == null) return '[object Undefined]'
    if (value == null) {
        return value === undefined ? '[object Undefined]' : '[object Null]'
    }
    return toString.call(value)}
Copy after login

好了到最后,大家平时对类型检测的态度是什么样的呢?

相关免费学习推荐:javascript(视频)

The above is the detailed content of JavaScript Topic 6: Type Detection. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:csdn.net
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template