如何解决为什么 ref.deref() 在 Safari 控制台调试中没有结果?
我是这方面的新生,我正在关注 WWDC21 会议进行一些测试,但是当我执行 createFourStopwatchesDemo 时,safari 以没有任何结果结束。它应该打印更多信息,如“秒表启动”...
环境:Mac OSX 11.4 Safari Technology Prview 14.2
Safari 控制台只显示如下当我执行 'createFourStopwatchesDemo()'
这是我的详细代码:
//Example1
//class with public variable and function
class StopWatchWithOneButton {
_startTime = 0;
click(){
if (!this._startTime) {
this.start();
}else{
this.stop();
}
}
start() {
this._startTime = Date.now();
console.log('StopWatch started');
}
stop() {
let duration = Date.now() - this._startTime;
this._startTime = 0;
console.log('StopWatch stopped after %d ms',duration);
}
}
//class with private variable and function
class PrivateStopWatchWithOneButton {
#_startTime = 0;
static #stopWatchCount = 0;
click(){
if (!this.#_startTime) {
this.#start();
}else{
this.#stop();
}
}
#start() {
PrivateStopWatchWithOneButton.#stopWatchCount++;
this.#_startTime = Date.now();
console.log('StopWatch started');
}
#stop() {
PrivateStopWatchWithOneButton.#stopWatchCount--;
let duration = Date.now() - this.#_startTime;
this.#_startTime = 0;
console.log('StopWatch stopped after %d ms',duration);
}
}
function sleep(ms) {
return new Promise(resolve => setTimeout(resolve,ms));
}
async function demo(){
// console.log(StopWatchWithOneButton._startTime);
var counter = new StopWatchWithOneButton();
counter.click();
console.log('sleep for a while,' + counter._startTime);
await sleep(2000);
console.log('ake up');
counter.click();
//private #_startTime
var priCounter = new PrivateStopWatchWithOneButton();
// console.log('sleep for a while of Private:' + priCounter.#_startTime);//syntax error
priCounter.click();
await sleep(2000);
priCounter.click();
}
//Example2: weak reference
//WeakRef(obj): create weak reference to an object
//use FinalizationRegistry to delete object automaticaly
const allStopWatches = new Map();
var nextAvailableIdentifier = 1;
function removeStopwatch(identifier){
allStopWatches.delete(identifier);
}
const finalizationRegistry = new FinalizationRegistry(removeStopwatch);
function createStopwatch(){
let identifier = nextAvailableIdentifier++;
let stopwatch = new StopWatchWithOneButton();
allStopWatches.set(identifier,new WeakRef(stopwatch));
finalizationRegistry.register(stopwatch,identifier);//the first parameter is an object
return stopwatch;
}
function clickAllStopwatches(){
for(let weakStopwatch in allStopWatches){
//weakStopwatch.deref(): Get the element from the weak reference,if it still exists
weakStopwatch.deref()?.click();
}
}
function createFourStopwatchesDemo(){
for (let i = 0; i < 4; i++) {
let currStop = createStopwatch();
}
clickAllStopwatches();
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。