用户:Ranto2012/沙盒
代码示例
编辑类与继承与多态
编辑class Base {
name = "base";
printName() {
console.log(this.name);
}
}
class ChildA extends Base {
name = "a";
}
class ChildB extends Base {
name = "b";
}
obj1 = new Base();
obj1.printName();
obj2 = new ChildA();
obj2.printName();
obj3 = new ChildB();
obj3.printName();
输出结果:
base
a
b
异步与回调与Promise
编辑function a1() {
console.log("from a1");
}
function a2() {
console.log("from a2");
}
function b(cb) {
setTimeout(() => {
console.log("from b");
cb();
}, 1000)
}
async function c() {
await new Promise((resolve) => {
setTimeout(() => {
console.log("from c");
resolve();
}, 1000);
})
}
function test1() {
console.log("test1");
b(a1);
}
async function test2() {
console.log("test2");
const p = c();
a1();
await p;
a2();
}
test1()
结果:
test1
from b
from a1
test2()
结果:
test2
from a1
from c
from a2