gpt4 book ai didi

javascript - TypeScript 属性中的 readonly 与 get 之间有什么区别?

转载 作者:数据小太阳 更新时间:2023-10-29 04:39:32 25 4
gpt4 key购买 nike

在 TypeScript 中将属性声明为 readonly 与通过 get() 创建它之间是否存在功能差异?两者的行为相同,但最好知道除了偏好之外是否还有理由使用其中一个。

最佳答案

它对生成的 JavaScript 有所不同:getter 将是一个访问器属性(例如,函数),readonly 属性将是一个数据属性。这:

class Example {
get foo(): string {
return "foo";
}
readonly bar: string = "bar";
}

如果您以 ES2015+ 为目标,则转换为:

"use strict";
class Example {
constructor() {
this.bar = "bar";
}
get foo() {
return "foo";
}
}

Live on the playground

或者如果你的目标是 ES5+,则为:

"use strict";
var Example = /** @class */ (function () {
function Example() {
this.bar = "bar";
}
Object.defineProperty(Example.prototype, "foo", {
get: function () {
return "foo";
},
enumerable: true,
configurable: true
});
return Example;
}());

Live on the playground

请注意,尽管 TypeScript 认为 bar 是只读的,但在运行时没有任何强制执行。另一方面,foo 即使在运行时也是只读的。 (虽然如果您真的想要,您可以使用 Object.defineProperty 通过重新配置属性来打败它。)

关于javascript - TypeScript 属性中的 readonly 与 get 之间有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57805276/

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