ES6 Class Module模块化 案例

来源:互联网 发布:英雄联盟和刀塔2 知乎 编辑:程序博客网 时间:2024/06/05 11:38

前言

这篇通过简单说明ES6 Class和Module这个两个成员。并且用这两个成员制造模块化。

Class说明

Class(类)作用对象模块,也就是一个方法集合,像以前的prototype父类一样,也一样可以通过new来实例,用法基本一样。所以只是换种方法写继承而已。我个人觉得Class加入使代码更加直观,更容易理解。

案例

Class简单一个new实例:

ES5

var name = "tom";var age = "20";function model(){}model.prototype = {    constructor(obj){        this._config = obj;        console.log(obj.name+"年龄"+obj.age)    },    setValue(key,value){         this._config[key]=value;    },    getValue(key){        console.log(this._config[key]?this._config[key]:'no have '+key);    }}     var example = new model() //tom年龄20example.constructor({name,age})example.setValue("sex","man")example.getValue("sex") //manexample.getValue("day") //no have day

ES6

const name = "tom";const age = "20";class model{    constructor(obj){/*就是new命令自动跳用方法。一个类必须要有constructor,如果没定义,有默认添加一个空的。*/        this._config = obj;        console.log(obj.name+"年龄"+obj.age)    }    setValue(key,value){      this._config[key]=value;    }    getValue(key){      console.log(this._config[key]?this._config[key]:`no have ${key}`);    }}var example = new model({name,age}) //tom年龄20example.setValue("sex","man")example.getValue("sex") //manexample.getValue("day") //no have day


Module说明:

Module就是把js做成模块化的一个核心,就像require.js那样导出和加载一个js。可以把一个js分拆出来加载,也可以整体加载。js一直没有模块概念,Module的加入是为了解决模块化的。

export命令

下面分别输出one,two,three这3个变量。
export.js

exprot var one = "1";exprot var two = "2";exprot var three = "3";


import命令

通过export命令定义模块的对外接口后,其他js文件通过import命令来加载文件。

import {one,two,three} from "./export"; //选择对象加载import * from "./export"; //整体加载


一个完整模块构造模型

parent.js

const name = "tom";const age = "20";class Parent{  hw(){    console.log(`hello world`)  }  static obj(){      console.log('obj')/*表示为静态方法不回呗实例继承,而是直接通过类调用。*/    }}  var parent = new Parent()parent.hw()//hell worldexport{name,age,Parent}


child.js

import {name,age,Parent} from './parent'class Child extends Parent{    constructor(obj){/*就是new命令自动跳用方法。一个类必须要有constructor,如果没定义,有默认添加一个空的。*/        super()//调用父类的constructor()        this._config = obj;        console.log(obj.name+"年龄"+obj.age)    }    hw(){      console.log("hw")    }    set val(value){      this._config.name = value;      console.log(`name=${value}`)    }    get val(){      console.log(this._config.name);    }}Child.obj()//obj 继承父类static方法var model = new Child({name,age}) //tom年龄20model.hw()//hwmodel.val = "jock"; //name=jockmodel.val//jock

附:ES6转换ES2015

http://blog.csdn.net/rth362147773/article/details/78275551