Home>Article>Web Front-end> JavaScript Topic 6: Type Detection
JavaScriptSpecial topic on data type detection
##Directory
(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~1. typeof
typeof:OperatorReturns a string indicating the type of the uncalculated operand.
typeof null => 'object'and
typeof function(){} => 'function '
Object, we cannot distinguish which kind of Object it is:
typeof [] === 'object'; //truetypeof {} === 'object'; //truetypeof null === 'object'; //true
Summary
When detecting the original type of Js, excepttypeof nullreturns
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 chainDefinition
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); // trueNote 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 .
class extendsand
prototype chain rulescan be matched:
class
class Base {}class Current extends Base {}const obj = new Current();console.log(obj instanceof Current); // trueconsole.log(obj instanceof Base); // true
Prototype chain
function Foo() {}function Bar() {}Bar.prototype = new Foo();const obj = new Bar();console.log(obj instanceof Bar); // trueconsole.log(obj instanceof Foo); // trueNote 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
Summary
Instanceof uses the prototype chain to judge. In fact, as long as a prototype of typeTypeis on the prototype chain of a
object obj, then
obj instanceof Typeis 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 chainDefinition
Return theObject that creates the instance objectReference 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); // falseThe 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
Question
4. What is stringTag?
4.1 stringTag——type tag If you have seen the early implementation of some libraries, you will find thatObject.prototype.toStringis used to do type judgment way, they will have a string tag of the data type, called
stringTag;
Definition
toString()The method returns a string representing the object.
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]';}
toString时都做了什么?
这里直接将冴羽大大的总结搬了过来:
When the toString method is called, the following steps are taken:
- If the this value is undefined, return “[object Undefined]”.
- If the this value is null, return “[object Null]”.
- Let O be the result of calling ToObject passing the this value as the argument.
- Let class be the value of the [[Class]] internal property of O.
- Return the String value that is the result of concatenating the three Strings "[object ", class, and “]”.
当 toString 方法被调用的时候,下面的步骤会被执行:
注意
有几点我们需要注意:
对象
;五、实现几个数据检测的方法
好了看了几款常用的类型判断方法后,我们可不可以实现自己的类型判断工具?就利用上述提到的一个或多个方法。我们自己动手丰衣足食~
注意,我们认为null不是一个对象,它就是null~
function isObject(value) { const type = typeof value; return value != null && (type === 'object' || type === 'function');}
function isNull(value) { return value === null;}
function isFunction(value) { return typeof value === 'function';}
var isArray = Array.isArray || function( value ) { return type(value) === "array";}
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)}
好了到最后,大家平时对类型检测的态度是什么样的呢?
相关免费学习推荐: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!