Table of Contents
basic
symbol for
symbol keyfor
symbol cannot be forced to convert
Getting the symbol key in obj
Symbol.hasInstance
Symbol.isConcatSpreadable
Symbol.toPrimitive
Home Web Front-end JS Tutorial Introduction to Symbol related knowledge in ES6 (code example)

Introduction to Symbol related knowledge in ES6 (code example)

Nov 26, 2018 pm 03:59 PM
javascript typescript

This article brings you an introduction to Symbol-related knowledge in ES6 (code examples). It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

symbol is a type introduced in es6, and it also belongs to the category of primitive types (string, number, boolean, null, undefined, symbol)

basic

let name = Symbol('xiaohesong')
typeof name // 'symbol'
let obj = {}
obj[name] = 'xhs'
console.log(obj[name]) //xhs
Copy after login

symbol for

This thing is shareable. When it is created, it will check whether the symbol of this key is found globally. If it exists, the symbol will be returned directly. If it does not exist, it will be created and registered globally. .

let uid = Symbol.for("uid");
let object = {
    [uid]: "12345"
};

console.log(object[uid]);       // "12345"
console.log(uid);               // "Symbol(uid)"

let uid2 = Symbol.for("uid");

console.log(uid === uid2);      // true
console.log(object[uid2]);      // "12345"
console.log(uid2);              // "Symbol(uid)"
Copy after login
The sharing mentioned here is global sharing, similar to global scope, and is shared in the entire environment.

symbol keyfor

let uid = Symbol.for("uid");
console.log(Symbol.keyFor(uid));    // "uid"

let uid2 = Symbol.for("uid");
console.log(Symbol.keyFor(uid2));   // "uid"

let uid3 = Symbol("uid");
console.log(Symbol.keyFor(uid3));   // undefined
Copy after login

The shared symbol uid3 does not exist in the global registry .So the corresponding key cannot be obtained. It can be seen that this is to obtain the corresponding key.

symbol cannot be forced to convert

let uid = Symbol('uid')
uid + ''
Copy after login

An error will be reported here. According to the specification, it will convert uid into Strings are added. If you really want to add, you can add String(uid) first and then add, but at present, it seems to be meaningless.

Getting the symbol key in obj

let uid = Symbol('uid')
let obj = {
    [uid]: 'uid'
}

console.log(Object.keys(obj)) // []
console.log(Object.getOwnPropertyNames(obj)) // []
console.log(Object.getOwnPropertySymbols(obj)) // [Symbol(uid)]
Copy after login

es6 For this, the Object.getOwnPropertySymbols method was added.

Do you feel that Symbols are rarely used? In fact, there are still a lot of them used internally in es6.

Symbol.hasInstance

Every function has this method. Maybe you are not very familiar with this method, but it is actually what instanceof does. That's right, es6 rewrites this method for you.

function Xiao(){}
const xiao = new Xiao
xiao instanceof Xiao // true
Copy after login

Actually es6 does that for you

Xiao[Symbol.hasInstance](xiao)
Copy after login

This is an internal method and does not support rewriting. Of course, we can rewrite it on the prototype.

Object.definePrototype(Xiao, Symbol.hasInstance, {
   value: (v) : Boolean(v)
})
const x = new Xiao
x instanceof Xiao //true
0 instanceof Xiao //false
1 instanceof Xiao //true
Copy after login

It can be found that we rewrite it to return whether the corresponding value is a boolean type.

Symbol.isConcatSpreadable

This is different from other properties. It does not exist on some standard objects by default. Simply use

let objs = {0: 'first', 1: 'second', length: 2, [Symbol.isConcatSpreadable]: true}
['arrs'].concat(objs) //["arrs", "first", "second"]
Copy after login

Symbol.toPrimitive

. This is more useful. When performing type conversion, the object will try to convert to the original type, that is, through toPrimitive .This method exists on prototypes of standard types.
When performing type conversion, toPrimitive will be forced to call a parameter. In the specification, this parameter is called hint. This parameter has three values ​​('number ', 'string', 'default') one of them.
As the name suggests, string returns string, number returns number, and default is not specified, the default.
So what is the default situation? In most cases, the default is numeric mode. (Except for date, its default situation is regarded as string mode)
In fact, there are not many default situations that are called during type conversion. Such as (==, ) or when passing parameters to the constructor parameters of Date.

  • number mode behavior in the case of numbers (priority from high to low)

  • First call valueOf, if it is a primitive type, Then return.

  • If the previous value is not the original value, then try to call toString. If it is the original value, then return

  • If it does not exist, then Report an error

  • string mode In the case of strings, the behavior is slightly different (priority from high to low)

  • First call toString , if it is the original value, then return

  • If the previous value is not the original value, then try to call valueOf, if it is the original value, then return

  • Throwing an error

Well, it feels a bit confusing, yes, let me explain the code.

let obj = {
    valueOf: function(){console.log('valueOf')},
    toString: function(){console.log('toString')}
}
// console.log value is
obj + 2 //valueOf
obj == 2 // valueOf
Number(obj) // valueOf
String(obj) // toString
Copy after login

Through the above output, you can find that in most cases valueOf.
including the default case, the default is the number mode called, and most of them are the numbers called. mode, you can find that toString is the mode that calls string. So you can think that it is basically a numeric mode, unless it is a string mode.
Not very clear about this calling mode? It's okay, es6 exposes this internal method to the outside world, we can rewrite it and output the type of the hint. Come to

function Temperature(degrees) {
    this.degrees = degrees;
}

Temperature.prototype[Symbol.toPrimitive] = function(hint) {
    console.log('hint is', hint)
};

let freezing = new Temperature(32);

freezing + 2 // ..
freezing / 2 // ..
...
Copy after login

the above types, you can try.

The above is the detailed content of Introduction to Symbol related knowledge in ES6 (code example). For more information, please follow other related articles on the PHP Chinese website!

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to implement an online speech recognition system using WebSocket and JavaScript How to implement an online speech recognition system using WebSocket and JavaScript Dec 17, 2023 pm 02:54 PM

How to use WebSocket and JavaScript to implement an online speech recognition system Introduction: With the continuous development of technology, speech recognition technology has become an important part of the field of artificial intelligence. The online speech recognition system based on WebSocket and JavaScript has the characteristics of low latency, real-time and cross-platform, and has become a widely used solution. This article will introduce how to use WebSocket and JavaScript to implement an online speech recognition system.

WebSocket and JavaScript: key technologies for implementing real-time monitoring systems WebSocket and JavaScript: key technologies for implementing real-time monitoring systems Dec 17, 2023 pm 05:30 PM

WebSocket and JavaScript: Key technologies for realizing real-time monitoring systems Introduction: With the rapid development of Internet technology, real-time monitoring systems have been widely used in various fields. One of the key technologies to achieve real-time monitoring is the combination of WebSocket and JavaScript. This article will introduce the application of WebSocket and JavaScript in real-time monitoring systems, give code examples, and explain their implementation principles in detail. 1. WebSocket technology

How to use JavaScript and WebSocket to implement a real-time online ordering system How to use JavaScript and WebSocket to implement a real-time online ordering system Dec 17, 2023 pm 12:09 PM

Introduction to how to use JavaScript and WebSocket to implement a real-time online ordering system: With the popularity of the Internet and the advancement of technology, more and more restaurants have begun to provide online ordering services. In order to implement a real-time online ordering system, we can use JavaScript and WebSocket technology. WebSocket is a full-duplex communication protocol based on the TCP protocol, which can realize real-time two-way communication between the client and the server. In the real-time online ordering system, when the user selects dishes and places an order

How to implement an online reservation system using WebSocket and JavaScript How to implement an online reservation system using WebSocket and JavaScript Dec 17, 2023 am 09:39 AM

How to use WebSocket and JavaScript to implement an online reservation system. In today's digital era, more and more businesses and services need to provide online reservation functions. It is crucial to implement an efficient and real-time online reservation system. This article will introduce how to use WebSocket and JavaScript to implement an online reservation system, and provide specific code examples. 1. What is WebSocket? WebSocket is a full-duplex method on a single TCP connection.

JavaScript and WebSocket: Building an efficient real-time weather forecasting system JavaScript and WebSocket: Building an efficient real-time weather forecasting system Dec 17, 2023 pm 05:13 PM

JavaScript and WebSocket: Building an efficient real-time weather forecast system Introduction: Today, the accuracy of weather forecasts is of great significance to daily life and decision-making. As technology develops, we can provide more accurate and reliable weather forecasts by obtaining weather data in real time. In this article, we will learn how to use JavaScript and WebSocket technology to build an efficient real-time weather forecast system. This article will demonstrate the implementation process through specific code examples. We

Simple JavaScript Tutorial: How to Get HTTP Status Code Simple JavaScript Tutorial: How to Get HTTP Status Code Jan 05, 2024 pm 06:08 PM

JavaScript tutorial: How to get HTTP status code, specific code examples are required. Preface: In web development, data interaction with the server is often involved. When communicating with the server, we often need to obtain the returned HTTP status code to determine whether the operation is successful, and perform corresponding processing based on different status codes. This article will teach you how to use JavaScript to obtain HTTP status codes and provide some practical code examples. Using XMLHttpRequest

JavaScript and WebSocket: Building an efficient real-time image processing system JavaScript and WebSocket: Building an efficient real-time image processing system Dec 17, 2023 am 08:41 AM

JavaScript is a programming language widely used in web development, while WebSocket is a network protocol used for real-time communication. Combining the powerful functions of the two, we can create an efficient real-time image processing system. This article will introduce how to implement this system using JavaScript and WebSocket, and provide specific code examples. First, we need to clarify the requirements and goals of the real-time image processing system. Suppose we have a camera device that can collect real-time image data

How to get HTTP status code in JavaScript the easy way How to get HTTP status code in JavaScript the easy way Jan 05, 2024 pm 01:37 PM

Introduction to the method of obtaining HTTP status code in JavaScript: In front-end development, we often need to deal with the interaction with the back-end interface, and HTTP status code is a very important part of it. Understanding and obtaining HTTP status codes helps us better handle the data returned by the interface. This article will introduce how to use JavaScript to obtain HTTP status codes and provide specific code examples. 1. What is HTTP status code? HTTP status code means that when the browser initiates a request to the server, the service

See all articles