用戶: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