ES6系列学习(6)模块、Babel、Polyfill、ES6继承

缺乏、安全感 2022-02-13 15:55 1187阅读 0赞

1.ES6模块

  1. //config.js
  2. export const apiKey = 'abc123';
  3. export const age = 12;
  4. export function greet(name){
  5. };
  6. //
  7. import { apiKey ,age , greet} from './config'

slug:可以将各种各样的用户名转换成-连接的用户名,地址:https://www.npmjs.com/package/slug

2.使用SystemJS打包ES模块

和Webpack一样是打包工具,但是不用复杂配置。

https://www.npmjs.com/package/systemjs

3.Babel

babel中文网:https://www.babeljs.cn/

4.Polyfill

babel只能转换语法而不是去增加或修改原有ES6新的属性和方法。polyfill就是为了解决这种情况,也能抚平不同浏览器之间对js实现的差异。

babel/polyfill使用:https://www.babeljs.cn/docs/babel-polyfill

5.原型继承

  1. //ES5的原型继承
  2. function User(name,email){
  3. this.name = name;
  4. this.email = email;
  5. }
  6. User.prototype.info = function(){
  7. console.log('Hi I am ...');
  8. }
  9. const codecasts = new User('','');
  10. codecasts.info()
  11. //ES6的class继承
  12. class User{
  13. //类中构造函数
  14. constructor(name,email){
  15. this.name = name;
  16. this.email = email;
  17. }
  18. //类中方法
  19. info(){
  20. }
  21. //静态方法(只能在原型对象上调用,不能在实例上调用,例如Array.from())
  22. static description(){
  23. }
  24. //get/set设置和获取属性
  25. set github(value){
  26. this.girhubName = value;
  27. }
  28. get github(){
  29. return `https://github.com/${this.githubName}`
  30. }
  31. }
  32. const codecasts = new User('','');
  33. codecasts.github = 'laravist';
  34. codecasts.github

ES5和ES6的继承:

专门写一篇介绍

6.类的扩展

继承一个类:

  1. class Aimal{
  2. constructor(name){
  3. this.name;
  4. this.belly = [];
  5. }
  6. eat(food){
  7. this.belly.push(food);
  8. }
  9. }
  10. class Dog extends Animal{
  11. constructor(name,age){
  12. super(name); //类似于es5的Animal.call(this,name,age);
  13. this.age = age;
  14. }
  15. bark(){
  16. console.log('');
  17. }
  18. }
  19. const lucky = new Dog('lucky',2);
  20. lucky

子类必须在constructor方法里调用super方法,否则不能新建实例。这是因为子类没有属于自己的this对象,而是继承了父类的this对象而对其进行加工。显然,只有调用了super方法之后,才可以使用this。

7.ES6的class扩展内建对象数组

下面两种继承方式输出结果不一样

  1. //1 super()创建this值指向基类Array,MyArray这个子类在这个基类this上修改,所以this的值可以访问基类上的功能的
  2. class MyArray extends Array{
  3. constructor(){
  4. super();
  5. }
  6. }
  7. //2 子类MyArray创建this的值,this的值指向MyArray的实例,然后调用基类构造函数,Array的其他属性会修饰这个this
  8. function MyArray(){
  9. Array.apply(this,arguments);
  10. }
  11. const colors = new MyArray();
  12. colors[0] = 'red';
  13. console.log(colors.length); //undefined
  14. colors.length = 0;
  15. console.log(colors[0]) //red

发表评论

表情:
评论列表 (有 0 条评论,1187人围观)

还没有评论,来说两句吧...

相关阅读

    相关 ES6-模块

    1. 模块化的标准 (1)commonJS标准(node.js采用) (2)AMD标准(require.js采用) (3)ES6模块 2. 定义模块 export,可

    相关 ES6--模块

    概述 在 ES6 前, 实现模块化使用的是 RequireJS 或者 seaJS(分别是基于 AMD 规范的模块化库, 和基于 CMD 规范的模块化库)。 ES6 引入