JS面向对象基础

100 阅读1分钟

ES6中的类

  • 类的写法

    class Person{
      	height="178cm";
        constructor(name,age){
            //属性
            this.name = name;
            this.age = age;
        }
        //方法
        getName(){
            console.log("姓名是:"+this.name);
        }
    }
    let student = new Person("张三",20);
    student.getName();
    
    
  • 静态方法和属性:实例不会继承的属性和方法

    class Person{
        //静态方法
        static hobby(){
            console.log("喜欢篮球");
        }
    }
    //静态属性
    Person.height = "178cm";
    //通过类来调用
    Person.hobby();
    console.log(Person.height);
    
  • 类的继承

    class Dad{
        name = "张三";
        age = 40;
        constructor(height){
            this.height = height;
        }
        hobby(){
            console.log("喜欢篮球");
        }
    }
    class Son extends Dad{
        constructor(height){
            //表示父类的构造函数
            super(height);
        }
    }
    

es6模块化

  • 模块化,独立命名空间,多个script标签会导致变量污染

  • 浏览器默认模块化 script 里加入 "type=module";

  • 导出 关键字 export

    • 导出 方式一 :

      export { a ,b , c}
      
    • 导出方式二 关键字 "as"

      export { a as aa ,b , c}
      
    • 导出方式三

      export let c = ()=>{console.log("I am function...")}
      
    • 导出方式四

      export default a;
      
      • 等同

        export {a as default};
        
    • export 可以导出多个,export default 只能导出一个;

  • 导入方式:关键字 import

    • export导出的,命名要保持一致

      import {aa , b , c} from './moduleb.js';
      
    • export导出的,命名可以自定义;

      import myfn from './moduleb.js';
      
    • 通配符 "*"方式导入

      import * as obj from './moduleb.js';
      
  • 按需导入(延迟导入)

​ import 方法;

document.onclick =async function(){
    // import {fn1} from  './fn.js';
    let res = await import("./fn.js");
    console.log(res);
}