gpt4 book ai didi

javascript - 在javascript中有没有类似python的 `with`语句的东西?

转载 作者:行者123 更新时间:2023-12-05 08:11:01 27 4
gpt4 key购买 nike

python 中的 with 语句对于清理资源很有用,例如

with open('file.txt', 'w') as f:
// do something with the file

代码的编写者不必担心关闭文件,因为 open 函数的编写者已经实现了必要的东西来清理文件资源。

实现此功能的 javascript 中有哪些常见模式?

最佳答案

我能够在 typescript 中快速编写类似 Python 的上下文管理器的东西。希望有人发现有帮助

interface ContextManager<T> {
enter(): T;
exit()
}

class With {
private manager: ContextManager<any>;

private constructor() {
}

static context(manager: ContextManager<any>) {
const withBlock = new With();
withBlock.manager = manager;
return withBlock;
}

run(func) {
const obj = this.manager.enter();
func(obj);
this.manager.exit();
}
}

用法:

class Open implements ContextManager<string> {
private readonly name: string;

constructor(name: string) {
this.name = name;
}

enter(): string {
console.log("Start Context: " + this.name);
return this.name;
}

exit() {
console.log("End Context: " + this.name)
}

}


With.context(new Open("myfile.txt")).run((file) => {
console.log("Here I am reading off: "+ file)
})

输出:

Start Context: myfile.txt
Here I am reading off: myfile.txt
End Context: myfile.txt

关于javascript - 在javascript中有没有类似python的 `with`语句的东西?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67104447/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com