Introduction and opening introduction of the taro framework

Introduction and opening introduction of the taro framework

Taro is a framework launched by Jingdong Ao-Convex Lab, the purpose is to solve the multi-stage chaotic situation, and it is also a relatively new framework at present.
When we develop according to one model and one code, after the development is completed, the project will have the ability to be displayed on any terminal, which is a very cool experience to think about. So what are the advantages of taro, please see the picture below.
![image.png](https://img-blog.csdnimg.cn/img_convert/0f873a02ed723226c1ae03023d0e0b4f.png#clientId=uae406f8b-c2e5-4&crop=0&crop=0&crop=1&crop=1&from=paste&height=818&id= ueda29aa4&margin=[object Object ]&name=image.png&originHeight=818&originWidth=1500&originalType=binary&ratio=1&rotation=0&showTitle=false&size=1181909&status=done&style=none&taskId=u084f2faf-a6a2-4b36-8fe0-eb47789bbf 5&title=&width=1500)

Terminals currently supported by taro

1. WeChat applet
2, H5 mobile web page
3, Baidu applet
4, Alipay applet
5, quick app
6, reactnative
7, ByteDance applet
8, qq light application
taro is currently the front end that supports the most applets One of the frameworks shows that we can easily generate applications comparable to native apps. Therefore, if the company's application wants to promote the entire network and occupy the most traffic entrances, there is no problem in using taro.
Of course, uni-app also has such a similar function, the function of generating multi-terminal applications. And there is also a dedicated editor, which is very convenient for debugging. Below we will put a comparison chart of taro and uni-app and other frameworks: ![
image.png](https://img-blog.csdnimg.cn/img_convert /585006a042c0500b50b3bc5990f7aa07.png#clientId=uae406f8b-c2e5-4&crop=0&crop=0&crop=1&crop=1&from=paste&height=660&id=ueaa9a89d&margin=[object Object]&name=image.png&orig inHeight=660&originWidth=1365&originalType=binary&ratio=1&rotation=0&showTitle=false&size=88844&status =done&style=none&taskId=ud176fb2f-c1ee-4e77-928a-294b36b26f0&title=&width=1365)
It can be seen that the strength of Taro and the proportion of Taro framework in the front-end technology will be higher and higher. And what a great development experience it is to use a unified framework, a unified API, a unified code specification, and a unified code structure.
The layout of all mainstream platforms can be completed in one development, and the cost of manpower and time is reduced to the minimum, and it feels like saving 100 million.
Next, let's unveil the magical veil of Taro together.

Taro's environment construction and Hello World

Pre-knowledge

To learn this front-end framework, you need some pre-knowledge:
HTML, CSS, and JavaScript are the basic knowledge. At the very least, you need to know how to make simple static pages
and understand the MVVM framework. If you know the React framework, it is best
to understand ES6 related syntax. , as a currently popular framework and the front-end development in 2020 uses ES6 to standardize the code, which is more convenient for project development and management

Introduction to Taro compilation tool

Taro is a set of multi-terminal development solutions that follow the grammar specification of React. Using Taro, you only write a set of code, and then use Taro’s compilation tool to compile the source code separately, which can be reused on different terminals (WeChat applet, H5, RN, etc.) Run the code.

So the Taro compilation tool here is very important, here is a picture. ![image.png](https://img-blog.csdnimg.cn/img_convert/85db9cfd98f4d7eb57e8a8b620028fee.png#clientId=uae406f8b-c2e5-4&crop=0&crop=0&crop=1&crop=1&from=paste&height=546&id=ua afc1aad&margin=[object Object ]&name=image.png&originHeight=546&originWidth=528&originalType=binary&ratio=1&rotation=0&showTitle=false&size=267435&status=done&style=none&taskId=u67d2c56b-3afa-4e93-ae5a-38fef34a36 a&title=&width=528)

Installation of Taro development environment


1. The first step is to install @tarojs/cli (scaffolding tool), which also teaches development tools.
You can use npm or yarn to install globally, the command is as follows:

How to install npm

npm install -g @tarojs/cli

How to install yarn

yarn global add @tarojs/cli

After opening the command line, enter the above command.

2. After the installation is complete, you can create a project with scaffolding, the command is as follows:

taro init taro-dome

There is a small pit here. If you use npm to install scaffolding, there is a high probability of failure. These failures are mostly due to the restrictions of the domestic network environment. There are two solutions, the first is "fangqiang" to install, the second is to use yarn to perform dark transfer, I use yarn here.

Hello World program

Through the creation of the project above, our project has been established, and then the project is run, the command is as follows:

cd taro-dome
npm run dev:h5

The h5 mode is running here. If you want to run the applet, you can know the corresponding running mode according to the script setting in package.json. ![image.png](https://img-blog.csdnimg.cn/img_convert/ba10bc84c1b35c581242562fb30545ad.png#clientId=uae406f8b-c2e5-4&crop=0&crop=0&crop=1&crop=1&from=paste&height=634&id=u 0fc421db&margin=[object Object ]&name=image.png&originHeight=634&originWidth=808&originalType=binary&ratio=1&rotation=0&showTitle=false&size=138230&status=done&style=none&taskId=u1e498881-b3f9-4952-8668-3e43a843 6b5&title=&width=808)
After running, the page will display Hello World in the browser. The default port is 10086, as shown in the figure: ![image.png](https://img-blog.csdnimg.cn/img_convert/cc8f68689db61651a7c5cf7d0b06c32a.png#clientId=uae406f8b-c2e5 -4&crop=0&crop=0&crop=1&crop=1&from=paste&height=302&id=u688a40a4&margin=[object Object]&name=image.png&originHeight=302&originWidth=833&originalType=binary&ratio=1&rotation=0&showTitle=false&size=3 2604&status=done&style=none&taskId=u21860b89-49a3-4259 -895a-cd740c4f7b4&title=&width=833)

Taro generates applet code and previews it

Taro can generate multi-terminal codes. In the previous section, only the h5 display was generated. This time we will first generate the applet code and preview it.

Generate code for WeChat applets

npm run dev:weapp

After entering the command, the taro compiler automatically generates the applet code for us and puts it in the dist directory. ![image.png](https://img-blog.csdnimg.cn/img_convert/63fe54a447aa296e3a2b7cb6a765e914.png#clientId=uae406f8b-c2e5-4&crop=0&crop=0&crop=1&crop=1&from=paste&height=388&id= uda461acf&margin=[object Object ]&name=image.png&originHeight=388&originWidth=455&originalType=binary&ratio=1&rotation=0&showTitle=false&size=31075&status=done&style=none&taskId=u67daf35d-5cf2-4cf9-9ee6-b6ce325f7c4& title=&width=455) app.js, app.json
and app.wxss These are the files corresponding to WeChat applets. Those who have developed WeChat applets must feel very familiar with them. This is the strength of Taro, and the developer of the Taro framework must be a master of webpack development. Compile and generate Corresponds to terminal code, not a shell nest.

Preview the project in WeChat Developer Tools

Be careful
not to modify the dist directory in the WeChat developer tool, because this file is compiled by taro;
if you want to modify the original project in taro, then compile the modified content into the dist file by compiling

directory structure of taro

There will definitely be doubts before the introduction of the catalog. Taro is a multi-terminal unified framework. Earlier we used the editing tool to generate the codes of H5 and WeChat applets. Then how are other Alipay applets, Baidu applets, etc. generated?
These answers are in the scripts section of the project's package.json file:

"scripts": {
    
    
    "build:weapp": "taro build --type weapp",
    "build:swan": "taro build --type swan",
    "build:alipay": "taro build --type alipay",
    "build:tt": "taro build --type tt",
    "build:h5": "taro build --type h5",
    "build:rn": "taro build --type rn",
    "build:qq": "taro build --type qq",
    "build:quickapp": "taro build --type quickapp",
    "dev:weapp": "npm run build:weapp -- --watch",
    "dev:swan": "npm run build:swan -- --watch",
    "dev:alipay": "npm run build:alipay -- --watch",
    "dev:tt": "npm run build:tt -- --watch",
    "dev:h5": "npm run build:h5 -- --watch",
    "dev:rn": "npm run build:rn -- --watch",
    "dev:qq": "npm run build:qq -- --watch",
    "dev:quickapp": "npm run build:quickapp -- --watch"
  }

Let's take dev as an example to explain dev: Which platform is behind
weapp Wechat applet
h5 Mobile web is used for public accounts and browsers, etc.
swan Baidu applet
alipay Alipay applet
tt Bytebeat applet
qq QQ applet Program
jd, Jingdong applet
quickapp, quick app
rn React Native
, these types of execution are the same as those of the WeChat applet, just change the following to the corresponding mode

npm run dev:weapp
或
yarn dev:weapp

Let’s introduce taro’s project directory structure
dist directory
. This directory has already been seen in the WeChat applet code generated above. It is automatically generated when we preview. Every time we preview, it will be compiled into different files according to our preview terminal. , the above code is removed every time it compiles. Regenerate a new
config directory
. This is some configuration of the project. These configurations will be studied in depth in the future, but they are not understood yet. You can not configure them first, otherwise it will affect the dependencies required by the project to run
the node_modules project, which is to use npm install. The installed package is generally the src directory that
does not need to be modified. This is the most important. It is the source code directory of our project, and the development code is in it ** **


├── dist                   编译结果目录
├── config                 配置目录
|   ├── dev.js             开发时配置
|   ├── index.js           默认配置
|   └── prod.js            打包时配置
├── src                    源码目录
|   ├── pages              页面文件目录
|   |   ├── index          index 页面目录
|   |   |   ├── index.js   index 页面逻辑
|   |   |   └── index.css  index 页面样式
|   ├── app.css            项目总通用样式
|   └── app.js             项目入口文件
└── package.json

## taro uses new features of hooks ### Advantages and disadvantages of react hooks Since we want to use hooks to write, then we need to understand the advantages and disadvantages of reacthooks, why use hooks. #### Advantages of React Hooks · Easier to reuse code
· Refreshing code style
· Less code size
· Easier to find useless states and functions
· Easier to split components #### Disadvantages of React Hooks · State is not Synchronization
· Side effect code changes from active to reactive #### How to avoid the common problems of React Hooks Do not write too many dependencies in useEffect, divide these dependencies into multiple useEffects, which is easier to maintain If
you If you encounter the problem of out-of-sync state, you can consider manually passing parameters to the function. Such as: ```css // The count of showCount comes from the parent scope const [count,setCount] = useState(xxx); function showCount(){ console.log(count) }

// The count of showCount comes from the parameter
const [count,setCount] = useState(xxx);
function showCount©{ console.log© }

·一定要加入eslint-plugin-react-hooks这个插件,并且重视它的警告<br />·使用useRef来保存你的引用并在re-render的时候主动更新ref的对应属性,这样可以避免“引用是旧”的这个烦人的问题,但这种方式hack味道浓郁。
### 使用Hooks来改写Index组件
在src/pages/index/index.jsx文件:
```css
import Taro, { Component } from '@tarojs/taro'
import { View, Text } from '@tarojs/components'
import './index.less'

export default class Index extends Component {

  componentWillMount () { }

  componentDidMount () { }

  componentWillUnmount () { }

  componentDidShow () { }

  componentDidHide () { }

  config = {
    navigationBarTitleText: '首页'
  }

  render () {
    return (
      <View className='index'>
        <Text>Hello world!</Text>
      </View>
    )
  }
}


修改成hooks方式:
import Taro, {
    
     useState } from '@tarojs/taro'
import {
    
     View, Text } from '@tarojs/components'
import './index.less'

function Index(){
    
    
  
  const [userName] = useState('Hello Taro!')

  return (
    <View>
      <Text>{
    
    userName}</Text>
    </View>
  )
}

export default Index

Component value passing in taro

One of the benefits of using Taro is that it can be programmed in a componentized way, so writing components is a daily work in Taro.

Next, let's create a self-component first, and then pass the value of the component. Taro's component value transfer uses props like React's, so if you are familiar with React's component value transfer, it is easy to understand here.

Create a Child component under the src/pages/index folder in the Taro project

child.jsx component

import {
    
     View, Text } from '@tarojs/components'
function Child(){
    
    
  return ( 
    <View><Text>我是子组件</Text></View>
  )
}


然后在Index组件中引入,这里给出全部代码方便学习
import Taro, {
    
     useState } from '@tarojs/taro'
import {
    
     View, Text } from '@tarojs/components'
import './index.less'
import Child from "./child"

function Index(){
    
    
  
  const [userName] = useState('Hello Taro!')

  return (
    <View>
      <Text>{
    
    userName}</Text>
      <Child></Child>
    </View>
  )
}

export default Index

Pass value from parent component to child component

As mentioned above, the value passing of Taro is the same as that of React. The parent component passes the value to the child component through props; this is also possible
in Taro. Now modify the index.jsx code and pass the userName to the child component.

import Taro, {
    
     useState } from '@tarojs/taro'
import {
    
     View, Text } from '@tarojs/components'
import './index.less'
import Child from "./child"

function Index(){
    
    
  
  const [userName] = useState('Hello Taro!')

  return (
    <View>
      <Text>{
    
    userName}</Text>
      <Child userInfo={
    
    userName} ></Child>
    </View>
  )
}

export default Index

After passing, the subcomponent needs to increase the props parameter before receiving it with props.

import {
    
     View, Text } from '@tarojs/components'
function Child(props){
    
    
  return ( 
    <View>
        <Text>我是子组件</Text>
        <View><Text>接收来自父组件的值:{
    
    props.userInfo}</Text></View>
    </View>
  )
}

export default Child


这个组件间的传值非常的简单,当我们会用组件的形式编写页面和组件时,你就可以作一些小东西了。

But now you can see that we put the pages and components into a folder, and all use the jsx extension.

How to distinguish between those components and those pages?

In fact, it is distinguished by its own routing. As long as the routing is configured, it is a page, and if it is not configured, it is a component by default.

Let's take a look at the routing in Taro below!

Taro routing configuration and introduction

The routing in Taro is different from the routing in React. It is configured through the pages in app.jsx, and whoever is configured in the first array position will be the home page opened by default.
![image.png](https://img-blog.csdnimg.cn/img_convert/5ffdca3889e56155ab693c288681c19a.png#clientId=u0ac0d69f-3654-4&crop=0&crop=0&crop=1&crop=1&from=paste&height=271&id=u98 0eaf19&margin=[object Object ]&name=image.png&originHeight=271&originWidth=578&originalType=binary&ratio=1&rotation=0&showTitle=false&size=49191&status=done&style=none&taskId=ue8b56b04-41f8-4b1c-897e-eb6ce8c07c8& title=&width=578)

First configure routing

create a new page

Under the /src/pages/ folder, create a /blog folder, create a blog.jsx file under the folder, and write the following code:

import {
    
    View , Text} from '@tarojs/components'
function Blog(){
    
    
    return (
        <View>
            <Text>Blog Page</Text>
        </View>
    )
}
export default Blog

routing configuration

After you have a page, you can go to /src/app.jsx, and then add code to the pages array.

pages: [
    'pages/blog/blog',
    'pages/index/index'
],

One thing to note here is that you don't need to use import to introduce Blog pages, Taro does it for us automatically. After the modification is complete, you can take a look in the browser, and you can see that the default page has become a Blog page.

jump between pages

How to jump to the page

Taro provides 6 related navigation APIs, we can use these APIs to jump, it should be noted that some of these are dedicated to applets.

navigateTo: The most basic jump method, which can return to the parent page. All three terminals are supported, such as applets, H5, and React Native.
redirectTo: Do ​​not record the page of the previous episode, just jump directly. All three terminals are supported, Mini Program, H5, *React Native.
switchTab: To switch between tabs, this should be used together with Taro's navigation bar, supported by all three terminals, such as applets, H5, and React Native.
navigateBack: Go back to the previous page. This is often used in small programs and supported by all three terminals, such as small programs, H5, and React Native.
relaunch: Close all fronts and open to a page in the app. All three terminals are supported, such as applets, H5, and React Native.
getCurrentPages: Used to get current page information, this H5 is not supported. (Notice)

Page Jump Demo

To make a demo, we jump from the Blog page to the Index page, how to write our program.

For the convenience of learning, the entire code of blog.jsx is given here:

import Taro from '@tarojs/taro'
import {
    
    View , Text ,Button} from '@tarojs/components'
function Blog(){
    
    
    const gotoIndex=()=>{
    
    
        Taro.navigateTo({
    
    url:'/pages/index/index'})
    }
    return (
        <View>
            <Text>Blog Page</Text>
            <Button onClick={
    
    gotoIndex}>我要去Index页面</Button>
        </View>
    )
}
export default Blog

In this way, we have realized the jump of routing in Taro.

Taro routing parameters

Taro's routing parameters use the form of query strings

Parameter passing in Taro generally uses the form of a query string, that is, on the redirected url, add a ? question mark, and then follow it with parameters.

Now we use it on the Blog.jsx page, declare a variable in the form of useState, and then bring the value to the Index.jsx page through a jump.

import Taro ,{
    
    useState}from '@tarojs/taro'
import {
    
    View , Text ,Button} from '@tarojs/components'
function Blog(){
    
    

    const  [blogTitle,setBlogTitle]=useState('JSPang Blog')

    const gotoIndex=()=>{
    
    
        Taro.navigateTo({
    
    url:'/pages/index/index?blogTitle='+blogTitle})
    }
    return (
        <View>
            <Text>Blog Page</Text>
            <Button onClick={
    
    gotoIndex}>我要去Index页面</Button>
        </View>
    )
}
export default Blog

Receive passed parameters and display on the page

Now that the parameters can be passed, how to receive them in Index.jsx is actually very simple. Just use this.$router.params to receive.

Of course, we need to receive parameters, which can be done in useEffect() (useEffect is a method of React Hooks, students who don’t know it, please go to understand it),

useEffect(()=>{
    
    
setBlogTitle(this.$router.params.blogTitle)
},[])

For better learning, here is the entire code received, the code of index.jsx:

import Taro, {
    
      useState ,useEffect} from '@tarojs/taro'
import {
    
     View, Text } from '@tarojs/components'
import Child from './child.jsx'
import './index.less'

function Index(props){
    
    
  const [userName ,setUserName] = useState('Hello World!!!!')
  const [blogTitle,setBlogTitle] = useState('')
  useEffect(()=>{
    
    
    setBlogTitle(this.$router.params.blogTitle)
  },[])
  return ( 
    <View>
        <Text>{
    
    userName}</Text>
        <Child userName={
    
    userName}></Child>
        <View>{
    
    blogTitle}</View>
    </View>
  )

}

export default Index

Passing and receiving multiple parameters

For the reception of multiple parameters and multiple parameters, you only need to use & to link when passing, such as the following. (Students with experience in front-end development will definitely be familiar with this)

Taro.navigateTo({
    
    url:'/pages/index/index?blogTitle='+blogTitle+'&introduce='+introduce})

For the convenience of learning, here are all the codes of blog and jsx:

import Taro ,{
    
    useState}from '@tarojs/taro'
import {
    
    View , Text ,Button} from '@tarojs/components'
function Blog(){
    
    
introduce
    const  [blogTitle,setBlogTitle]=useState('JSPangBlog')
    const  [introduce,setIntroduce]=useState('111111')

    const gotoIndex=()=>{
    
    
        Taro.navigateTo({
    
    url:'/pages/index/index?blogTitle='+blogTitle+'&introduce='+introduce})
    }
    return (
        <View>
            <Text>Blog Page</Text>
            <Button onClick={
    
    gotoIndex}>我要去Index页面</Button>
        </View>
    )
}
export default Blog

The receiving parameter is the same as the single parameter receiving method, without too much introduction, just give the code directly,

import Taro, {
    
      useState ,useEffect} from '@tarojs/taro'
import {
    
     View, Text } from '@tarojs/components'
import Child from './child.jsx'
import './index.less'

function Index(props){
    
    
  const [userName ,setUserName] = useState('Hello World!!!!')
  const [blogTitle,setBlogTitle] = useState('')
  const  [introduce,setIntroduce]=useState('')
  useEffect(()=>{
    
    
    setBlogTitle(this.$router.params.blogTitle)
    setIntroduce(this.$router.params.introduce)
  },[])
  return ( 
    <View>
        <Text>{
    
    userName}</Text>
        <Child userName={
    
    userName}></Child>
        <View>{
    
    blogTitle}</View>
        <View>{
    
    introduce}</View>
    </View>
  )

}

export default Index

The method of JavaScript resource import

The introduction of JavaScript is similar to the introduction of React. For example, now we define a method called XieDaJiao (Xie Dajiao), and then define a method called liuying (Liu Ying).

In the /src directory, create a new /tools folder, then create an index.js file under the folder, and enter the following code.

export function xiedajiao(){
    
    
    console.log('我是谢大脚')
}

export function liuying(){
    
    
    console.log('我是刘英')
}




建立完成后,我们在blog.jsx文件中引入这个,需要用ES的解构的方式引入:
import {
    
    xiedajiao,liuying} from '../../tools'

Then the method used is also used to run in useEffect, as follows:

useEffect(()=>{
    
    
    xiedajiao()
    liuying()
},[])

How to import pictures

There are two ways for Taro to import pictures: import xxx from '…' and then use the method of putting xxx into the corresponding src and directly use the require method in src

Below is the code of blog.jsx, which is imported:

import Taro ,{
    
    useState ,useEffect}from '@tarojs/taro'
import {
    
    View , Text ,Button,Image} from '@tarojs/components'
import {
    
    xiedajiao,liuying} from '../../tools'
import newbbd  from '../../static/newbbd0001.jpg'

function Blog(){
    
    

    useEffect(()=>{
    
    
        xiedajiao()
        liuying()
    },[])



    const  [blogTitle,setBlogTitle]=useState('JSPangBlog')
    const  [introduce,setIntroduce]=useState('111111')
    const gotoIndex=()=>{
    
    
        Taro.navigateTo({
    
    url:'/pages/index/index?blogTitle='+blogTitle+'&introduce='+introduce})
    }
    return (
        <View>
            <Text>Blog Page111</Text>
            <Button onClick={
    
    gotoIndex}>我要去Index页面</Button>
            <View>
                <Image src={
    
    newbbd} width="100px" height="100px" />
            </View>
        </View>
    )
}

If you want to use require, change the src attribute of the Image component to:

<Image src={
    
    require('../../static/newbbd0001.jpg')} width="100px" height="100px" />

For more ways to import resources, you can take a look at the documentation of Taro resource introduction: http://taro-docs.jd.com/taro/docs/static-reference.html

By the way, Taro updates faster, so remember to update the Taro project

Taro provides an update command to update the CLI tool itself and Taro-related dependencies in the project

Update Taro CLI tool

yarn global add @tarojs/cli@latest

Precautions

Things we should pay attention to when using taro grammar

  1. Use two spaces for line breaks;
  2. A semicolon cannot be used at the end;
  3. Except for indentation, multiple spaces cannot be used;
  4. Uniformly use single quotation marks;
  5. Add a space after the keyword, such as Iif (condition) {}, there are spaces before the brackets;
  6. avoid redundant blank lines;
  7. Add spaces between the brackets and the function name when declaring a function,,,, such as function name (arg) { ... } run(function () { ... })
  8. Do not leave a space between the expansion operator and its expression, such as: fn(...args)
  9. When a semicolon is encountered, the space should be left behind and not before. For example: for (let i = 0; i < items.length; i++) {…}
  10. Leave spaces at the beginning and end of the code block, such as if (admin) {…}
  11. No spaces between parentheses such as getName(name)
  12. Do not add spaces in front of attributes such as user.name
  13. Add a space before the unary operator, such as: typeof !admin
  14. Leave a space at the beginning of the comment, such as: /_ comment _/
  15. Do not add spaces before and after the template in the template string, such as: const message = Hello, ${name}
  16. Add a space after the comma, such as const list = [1, 2, 3, 4] function greet (name, options) { … }
  17. Multiple lines of spaces are not allowed
  18. Add spaces around single-line code blocks
  19. always put commas at the end of the line
  20. The dot operator must be on the same line as the attribute
  21. When the function is called, the identifier and the parentheses do not leave spaces, such as console.log('hello')
  22. Leave a space between the colon and the value of the key-value pair, such as const obj = { 'key': 'value' }
  23. The variable and function names use the hump naming method uniformly: such as
function myFunction () {
    
     } const myVar = ‘hello’

Spaces should be left between string splicing operators (Infix operators) such as

const message = 'hello, ’ + name + ‘!’


The correct posture to check for NaN is to use isNaN() as in

if (isNaN(price)) {
    
     }

Legal strings are compared with type of such as

typeof name === ‘undefined’


24. Notes on arrays:

  1. don't destructure null values
  2. Use array literals instead of constructors such as
const {
    
     a: {
    
     b } } = foo


3) Do not extend native objects such as

Object.prototype.age = 21 //不行
  1. Pay attention to the style when object properties wrap
const user = {
    
     name: ‘Jane Doe’, age: 30, username: ‘jdoe86’ } // ✓ 正确
const user = {
    
    
name: ‘Jane Doe’,
age: 30,
username: ‘jdoe86’
}


Do not use unnecessary object values ​​as computed properties such as

const user = {
    
     name: ‘John Doe’ } //对


Avoid redefining functions in the nested code blocks of arguments.callee and arguments.caller,
and prohibit the use of Function constructors

const sum = new Function(‘a’, ‘b’, ‘return a + b’) // ✗ 错误

Self-invoking anonymous functions (IIFEs) are wrapped in parentheses

const getName = function () {
    
     }() // ✗ 错误
const getName = (function () {
    
     }()) // ✓ 正确
const getName = (function () {
    
     })() // ✓ 正确


Asynchronous programming using Promise or async functions

function* helloWorldGenerator() {
    
     // ✗ 错误
yield ‘hello’;
yield ‘world’;
return ‘ending’;
}
  1. Note on class names:

  2. Class names should start with a capital letter

const dog = new Animal() // ✓ 正确

2) Avoid reassigning the class name

class Dog extends Mammal {
    
    
constructor () {
    
    
super() // ✓ 正确
}
}

3) Please make sure super() has been called before using this

class Dog extends Animal {
    
    
constructor () {
    
    
this.legs = 4 // ✗ 错误
super()
}
}
  1. disallow redundant constructors
class Car {
    
    
constructor () {
    
     // ✗ 错误
super()
}
  1. Do not define redundant attributes in the class
class Dog {
    
    
bark () {
    
    }
bark () {
    
    } // ✗ 错误
}
  1. Parentheses are required when calling a parameterless constructor
function Animal () {
    
    }
const dog = new Animal // ✗ 错误
const dog = new Animal() // ✓ 正确
  1. new needs to be assigned to a variable after creating an object instance
new Character() // ✗ 错误
const character = new Character() // ✓ 正确
  1. When throwing an error with throw, throw an Error object instead of a string
throw ‘error’ // ✗ 错误
throw new Error(‘error’) // ✓ 正确


9) Do not reassign errors in catch

try {
    
    
// …
} catch (e) {
    
    
e = ‘new value’ // ✗ 错误
}




Guess you like

Origin blog.csdn.net/qq_39197547/article/details/125694118