zoukankan      html  css  js  c++  java
  • ES6学习笔记(五)

    import export

    这两个家伙对应的就是es6自己的 module功能。

    我们之前写的Javascript一直都没有模块化的体系,无法将一个庞大的js工程拆分成一个个功能相对独立但相互依赖的小工程,再用一种简单的方法把这些小工程连接在一起。

    这有可能导致两个问题:

    1. 一方面js代码变得很臃肿,难以维护

    2. 另一方面我们常常得很注意每个script标签在html中的位置,因为它们通常有依赖关系,顺序错了可能就会出bug

    在es6之前为解决上面提到的问题,我们得利用第三方提供的一些方案,主要有两种CommonJS(服务器端)和AMD(浏览器端,如require.js)

    ES6中的 import 和 export 和Java中的 import 和 export 用法基本一样。

    而现在我们有了es6的module功能,它实现非常简单,可以成为服务器和浏览器通用的模块解决方案。

    ES6模块的设计思想,是尽量的静态化,使得编译时就能确定模块的依赖关系,以及输入和输出的变量。CommonJS和AMD模块,都只能在运行时确定这些东西。

    看一个案例:

    回顾下require.js的写法。假设有两个js文件: index.jscontent.js,现在想要在index.js中使用content.js返回的结果。

    ES6前的引用写法

    首先定义

    //content.js
    define('content.js', function(){
        return 'A cat';
    })

    然后require

    //index.js
    require(['./content.js'], function(animal){
        console.log(animal);   //A cat
    })

    CommonJS写法

    //index.js
    var animal = require('./content.js')
    
    //content.js
    module.exports = 'A cat'

    ES6写法

    //index.js
    import animal from './content'
    
    //content.js
    export default 'A cat'

    export命令除了输出变量,还可以输出函数,甚至是类(react的模块基本都是输出类)

    //content.js
    
    export default 'A cat'    
    export function say(){
        return 'Hello!'
    }    
    export const type = 'dog'
    //index.js
    
    import { say, type } from './content'  
    let says = say()
    console.log(`The ${type} says ${says}`)  //The dog says Hello

    这里输入的时候要注意:大括号里面的变量名,必须与被导入模块(content.js)对外接口的名称相同。

    如果还希望输入content.js中输出的默认值(default), 可以写在大括号外面。

    //index.js
    
    import animal, { say, type } from './content'  
    let says = say()
    console.log(`The ${type} says ${says} to ${animal}`)  
    //The dog says Hello to A cat

    as 修改变量名

    在开发中可能遇到变量名重名或需要修改变量名时,ES6中可以用关键字 as 一键更名。

    //index.js
    
    import animal, { say, type as animalType } from './content'  
    let says = say()
    console.log(`The ${animalType} says ${says} to ${animal}`)  
    //The dog says Hello to A cat

    本篇参考资料

     
     
  • 相关阅读:
    const 函数
    为什么要进行初始化(C语言)
    关于矩阵的逆
    在写论文的参考文献时,有的段落空格很大,有的段落则正常,原因及解决方法(wps)
    C#递归搜索指定目录下的文件或目录
    try catch finally 执行顺序面试题总结
    关于try catch finally的执行顺序解释 都有return
    C# 序列号和反序列化 对象写入bin
    C# 序列化和反序列化 详解 对象和XML文件之间
    在C#中,Json的序列化和反序列化的几种方式总结
  • 原文地址:https://www.cnblogs.com/liyuspace/p/8436265.html
Copyright © 2011-2022 走看看