JavaScript 주제 6: 유형 감지

coldplay.xixi
풀어 주다: 2021-03-09 09:47:23
앞으로
2199명이 탐색했습니다.

JavaScript데이터 유형 감지에 대한 특별 주제

JavaScript 주제 6: 유형 감지

목차

  • 1, typeof
  • 2, instanceof
  • 3, constructor
  • 4. 스트링태그란 무엇인가요?
  • 다섯 가지 데이터 감지를 구현하는 방법
  • 마지막에 작성

(무료 학습 권장 사항: javascript 비디오 튜토리얼)

머리말

"JavaScript 데이터 우리는 Types의 단순 유형 감지 문제도 언급했습니다.

프론트엔드 학생으로서 우리 모두는 typeof와 instanceof를 사용하여 런타임 시 JavaScript 데이터의 유형을 결정할 수 있다는 것을 알아야 합니다. 그러면 이를 어떻게 결정합니까? 천 명이 천 가지 판단 방법을 쓸 것인가?

이 글에서는 일반적인 typeof, 객체별 인스턴스of, isNull, isNumber, isString 및 기타 방법으로 데이터 유형을 결정하는 방법에 대해 설명합니다~

JavaScript 주제 6: 유형 감지

1. typeof

typeof: 연산자는 계산되지 않은 피연산자의 유형을 나타내는 문자열을 반환합니다. 操作符返回一个字符串,表示未经计算的操作数的类型。

我们都知道,在 ES6 前,JavaScript 共六种数据类型,分别是:

  1. Undefined
  2. Null
  3. Boolean
  4. Number
  5. String
  6. Object

然而当我们使用 typeof 对这些数据类型的值进行操作的时候,返回的结果却不是一一对应,分别是:

  1. Undefined
  2. object – ***
  3. Boolean
  4. Number
  5. String
  6. Object

有一些意外,typeof null => 'object'typeof function(){} => 'function'

所以在大多数情况下我们可以使用typeof来检测基本数据类型,但是,检测得到的Object后,却无法区分是哪一种Object:

typeof [] === 'object'; //truetypeof {} === 'object'; //truetypeof null === 'object'; //true
로그인 후 복사

总结

在检测Js的原始类型时,除了typeof null返回object之外,其他的都返回对应类型名的小写字母。

二、instanceof

我们判断对象类型的时候,可以使用instanceof:

如果对原型及原型链不太熟悉的同学不妨看看这篇文章从原型到原型链

定义

instanceof 运算符用于检测构造函数的 prototype 属性是否出现在某个实例对象的原型链上。

实例

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
로그인 후 복사

注意instanceof是能匹配类型的父类的,所以arr instanceof Array和arr instanceof Object都是true,因为Object是Array的父类。

满足class extends原型链规则的父子类关系的对象都能被匹配:

class

class Base {}class Current extends Base {}const obj = new Current();console.log(obj instanceof Current); // trueconsole.log(obj instanceof Base); // true
로그인 후 복사

原型链

function Foo() {}function Bar() {}Bar.prototype = new Foo();const obj = new Bar();console.log(obj instanceof Bar); // trueconsole.log(obj instanceof Foo); // true
로그인 후 복사

注意如果我们修改obj的原型链能改变instanceof的结果:

function Other() {}obj.__proto__ = new Other();console.log(obj instanceof Other); // trueconsole.log(obj instanceof Foo); // false
로그인 후 복사

总结

instanceof借助了原型链来判断的实际上,只要一个类型Type的prototype在一个对象obj的原型链上,那么obj instanceof Type就是true,否则就是false。

三、constructor

有时候我们不希望匹配父类型,只希望匹配当前类型,那么我们可以用constructor来判断:

如果对原型及原型链不太熟悉的同学不妨看看这篇文章从原型到原型链

定义

返回创建实例对象的 Object 构造函数的引用。注意,此属性的值是对函数本身的引用,而不是一个包含函数名称的字符串。

实例

const arr = [];console.log(arr.constructor === Array); // trueconsole.log(arr.constructor === Object); // false
로그인 후 복사

对象的constructor会返回它的类型,而类型在定义的时候,会创建一个name只读属性,值为类型的名字。

class Foo {}console.log(Foo.name); // Fooconst foo = new Foo();console.log(foo.constructor === Foo); // trueconsole.log(foo.constructor.name === 'Foo'); // true
로그인 후 복사

疑问

  • constructor.name 一定就是正确的吗?
  • 我们可以修改它吗?

四、stringTag是什么?

4.1 stringTag——类型标签

如果你看过一些库的早期实现,你会发现使用Object.prototype.toString来做类型判断的方式,他们会数据类型的字符串标志,被称作stringTag

4.2 Object.prototype.toString

定义

toString()方法返回一个表示该对象的字符串。

每个对象都有一个 toString() 方法,当该对象被表示为一个文本值时,默认情况下,toString()

🎜우리 모두는 ES6 이전에는 JavaScript에 6가지 데이터 유형이 있었다는 것을 알고 있습니다. typeof를 사용하여 이러한 데이터 유형의 값에 대해 연산을 수행하면 반환된 결과는 각각 일대일 대응이 아닙니다. 🎜
    🎜Undefine🎜🎜object – ***🎜🎜Boolean🎜🎜Number🎜🎜String 🎜🎜 Object🎜
🎜몇 가지 놀라운 점이 있습니다. typeof null => 'object'typeof function(){} => 'function'🎜🎜그래서 대부분의 경우 typeof를 사용하여 기본 데이터 유형을 감지할 수 있지만 객체를 감지한 후에는 그것이 어떤 유형의 객체인지 구분할 수 없습니다. 🎜
var ostring = Object.prototype.toString;function isArray(it) {
  return ostring.call(it) === '[object Array]';}
로그인 후 복사
로그인 후 복사
🎜🎜Summary🎜🎜🎜Js 감지 시 기본 유형의 경우 객체를 반환하는 typeof null을 제외하고 다른 모든 유형은 해당 유형 이름의 소문자를 반환합니다. 🎜🎜🎜 2. 인스턴스 오브🎜🎜🎜객체 유형을 결정할 때 다음과 같이 인스턴스 오브를 사용할 수 있습니다. 🎜🎜프로토타입과 프로토타입 체인에 익숙하지 않은 경우 프로토타입에서 프로토타입 체인으로🎜🎜🎜정의를 읽어보세요. 🎜🎜 🎜instanceof 연산자는 생성자의 프로토타입 속성이 인스턴스 객체의 프로토타입 체인에 나타나는지 여부를 감지하는 데 사용됩니다. 🎜🎜🎜Instance🎜🎜
function isObject(value) {
    const type = typeof value;
    return value != null && (type === 'object' || type === 'function');}
로그인 후 복사
로그인 후 복사
🎜instanceof는 유형의 상위 클래스와 일치할 수 있으므로 arr 인스턴스of Array 및 arr 인스턴스of Object는 둘 다 참입니다. Object가 Array의 상위 클래스이기 때문입니다.
🎜🎜클래스 확장프로토타입 체인 규칙의 상위-하위 클래스 관계를 충족하는 개체는 일치될 수 있습니다. 🎜🎜🎜class🎜🎜
function isNull(value) {
    return value === null;}
로그인 후 복사
로그인 후 복사
🎜🎜Prototype chain🎜 🎜
function isFunction(value) {
    return typeof value === 'function';}
로그인 후 복사
로그인 후 복사
🎜obj의 프로토타입 체인을 수정하면 인스턴스of의 결과가 변경될 수 있습니다.
🎜
var isArray = Array.isArray || function( value ) {
    return type(value) === "array";}
로그인 후 복사
로그인 후 복사
🎜🎜Summary🎜🎜🎜Instanceof는 실제로 프로토타입 체인을 사용하여 판단합니다. Type 유형 중 하나의 프로토타입이 객체 obj의 프로토타입 체인에 있으면 obj instanceof Type은 true이고, 그렇지 않으면 false입니다. 🎜🎜🎜3. 생성자🎜🎜🎜때로는 부모 유형을 일치시키고 싶지 않고 현재 유형만 일치시키고 싶을 경우 생성자를 사용하여 판단할 수 있습니다. 🎜🎜프로토타입 및 프로토타입 체인에 익숙하지 않은 경우 , 이 기사를 읽어 보세요. 프로토타입에서 프로토타입 체인으로🎜🎜🎜Definition🎜🎜🎜 인스턴스 객체를 생성하는 Object 생성자에 대한 참조를 반환합니다. 이 속성의 값은 함수 이름을 포함하는 문자열이 아니라 함수 자체에 대한 참조입니다. 🎜🎜🎜 인스턴스🎜🎜
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)}
로그인 후 복사
로그인 후 복사
🎜 개체의 생성자는 해당 유형을 반환하고, 유형이 정의되면 해당 유형의 이름 값을 사용하여 이름 읽기 전용 속성이 생성됩니다.
🎜rrreee🎜🎜Question🎜🎜🎜🎜constructor.name이 반드시 맞나요? 🎜🎜수정해도 될까요? 🎜🎜🎜🎜4. 스트링태그란? 🎜🎜
4.1 stringTag - 유형 태그
🎜 일부 라이브러리의 초기 구현을 본 경우 Object.prototype.toString을 사용하여 유형을 판단하는 것을 볼 수 있습니다. 데이터 유형을 알고 있는 문자열 태그는 stringTag라고 합니다. 🎜
4.2 Object.prototype.toString
🎜🎜Definition🎜🎜🎜toString() 메서드 객체를 나타내는 문자열을 반환합니다. 🎜🎜각 개체에는 toString() 메서드가 있습니다. 개체가 텍스트 값으로 표현되는 경우 기본적으로 각 개체 개체 상속에서는 toString() 메서드를 사용합니다. . 🎜

如果此方法在自定义对象中未被覆盖,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:

  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 주제 6: 유형 감지

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

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

5.1 isObject

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

function isObject(value) {
    const type = typeof value;
    return value != null && (type === 'object' || type === 'function');}
로그인 후 복사
로그인 후 복사
5.2 isNull
function isNull(value) {
    return value === null;}
로그인 후 복사
로그인 후 복사
5.3 isFunction
function isFunction(value) {
    return typeof value === 'function';}
로그인 후 복사
로그인 후 복사
5.4 isArray
var isArray = Array.isArray || function( value ) {
    return type(value) === "array";}
로그인 후 복사
로그인 후 복사
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)}
로그인 후 복사
로그인 후 복사

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

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

위 내용은 JavaScript 주제 6: 유형 감지의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

관련 라벨:
원천:csdn.net
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!