一、类
class ClassA{
constructor(o){
Object.assign(this, o);
}
foo(){
console.log(this);
}
static bar(){
console.log("我是一个静态方法,不能通过实例化对象调用,只能通过类本身调用");
}
}
let a = new ClassA({
a : 1,
b : 2,
c : 3
});
ClassA.bar();
a.foo();
二、类的继承
class ClassA{
constructor(o){
if(new.target !== ClassA){
console.log("通过子类调用的");
}else{
console.log("被单独调用的");
}
Object.assign(this, o);
}
foo(){
console.log("我是classA的foo方法");
}
bar(){
console.log("我是classA的方法");
console.log(this);
}
}
class ClassB extends ClassA{
constructor(o){
super(o);
}
foo(){
super.foo();
console.log("我是classB的foo方法");
}
}
let b = new ClassB({a:1});
//ClassB.prototype -> b.__proto__
//b.foo();
三、模块与import语法
import() 返回一个promise对象
需要export暴露
let dir = "./export1.js";
if(true){
import(dir)
.then((module)=>{
let {a, foo, ClassA} = module;
foo();
console.log(a, foo, ClassA);
console.log(module.default);
})
}
(async function(){
let {c, b, foo} = await import(dir);
console.log(c, b, foo);
})()
let a = 1;
let b = 2;
function foo(){
console.log("foo");
}
//as取别名
export {a as c, b, foo}
export let a = 1;
export function foo(){
console.log("foo");
}
export class ClassA{
constructor(){}
}
export default class ClassA{
constructor(){}
}
import第二种用法,浏览器可能不支持,微信小程序已经支持
//代码编译阶段执行
import {b, foo} from "../../export/export1.js";
console.log(b, foo);
import ClassB from "../../export/export2.js";
new ClassB();
import * as modules from "../../export/export1.js";
console.log(modules);
let a = 1;
let b = 2;
let foo = function(){
console.log("foo");
}
export {a, b, foo};
export default class ClassA{
constructor(){
console.log(this);
}
}
网友评论