[Front-end] ES6 new features

Disclaimer: This article is a blogger original article, shall not be reproduced without the bloggers allowed. https://blog.csdn.net/cheidou123/article/details/91483726

A modular system

ES6 modular scope is to solve the problem, let JS become more organized.

1 export Export
  • ⑴ use the export keyword export
export const someValue = 1234
export const someValue0 = '1234'
export const someValue1 = {}
export let someValue2 = 1234
export let someValue3 = '1234'
export function someFunc = a => a+1
  • ⑵ can also write so
const someValue = 1234
function someFunc = a => a+1
let someObj = {}

export { someValue, someFunc, someObj}
  • ⑶ rename export
const someValue = 1234
function someFunc = a => a+1
let someObj = {}

export {
	someValue as exportNum,
    someFunc as exportFunc,
    someObj as exportObj
}
  • Export default
    default export in a file can only be used once
export defalut someValue = 1234
2 import Import
  • ⑴ import the specified variable
import { someValue } from './exportFile'  // 导入一个

import { someFunc, someObj } from './exportFile'   // 导入多个
  • Rename the variables specified introduced ⑵
import { someValue as importValue } from './exportFile'  // 重命名一个
import { someFunc as importFunc , someObj as importObj } from './exportFile' // 重命名多个
import {
    someValue,
    someFunc as importFunc 
}  // 导入多个,且部分重命名
  • ⑶ overall load
import * as importModule from './exportFile'  // 导入全部且挂载在 importModule 对象上

console.log(importModule.someValue)  // 1234
  • ⑷ import only module
import 'animate.css'
  • ⑸ Importing Defaults
// 就是使用 default 导出的变量,导入的时候我们要为它命名
import value from './exportFile'
Note 3

ES6 module output is a reference value. Different script to load this interface, get all the same instance.
E.g:

// mod.js
function C() {
  this.sum = 0;
  this.add = function () {
    this.sum += 1;
  };
  this.show = function () {
    console.log(this.sum);
  };
}

export let c = new C();
// x.js
import {c} from './mod';
c.add();

// y.js
import {c} from './mod';
c.show();

// main.js
import './x';
import './y';

Output is 1

Second-class and inheritance

1. Class

No pre-parsing class, instantiation must be placed below

class Person{  // Person类  它也是一个函数
    constructor(name){  // 构造函数
        this.name = name;
    }
    showName(){
        return this.name;
    }
}
var p1 = new Person('苏日俪格');
console.log(p1.showName());  // 苏日俪格
2. Inheritance
class Person{
    constructor(name){
        this.name = name;
    }
    showName(){
        return this.name;
    }
}
class SubPerson extends Person{
    constructor(name,job){
        super(name);    // 指向父类的构造函数
        this.job = job;
    }
    showJob(){
        return this.job;
    }
}
var p1 = new SubPerson('苏日俪格','前端开发');
console.log(p1.name);  // 苏日俪格
// console.log(p1.showName());  // 苏日俪格
// console.log(p1.job); // 前端开发

Guess you like

Origin blog.csdn.net/cheidou123/article/details/91483726