TypeScript 中的静态类方法和类外部(文件顶部)定义的函数之间有什么实际区别?
我知道与其他类和文件的可见性存在差异。当可见性不是问题时(函数/方法仅在一个类中使用),我们什么时候应该使用静态方法而不是在任何类外部定义的函数。
例子:
export class Foo {
constructor(bar: string) {
Foo.shout(bar);
}
private static shout(content: string) {
console.log(string.toUpperCase());
}
}
Run Code Online (Sandbox Code Playgroud)
VS
export class Foo {
constructor(bar: string) {
shout(bar);
}
}
function shout(content: string) {
console.log(string.toUpperCase());
}
Run Code Online (Sandbox Code Playgroud) 当获取和设置映射值时,映射必须以某种方式知道键是否等于另一个已设置的键。
如何在 Typescript 中实现复杂数据类型(自定义类)的相等性?在Java中我会重写equals方法,打字稿中有等价的方法吗?
就我而言,我有以下课程:
export class Path {
constructor(
private readonly scope: string[],
private readonly object: string[],
private readonly value: string
) { }
getScope(): string[] {
return this.scope;
}
getObject(): string[] {
return this.object;
}
getValue(): string {
return this.value;
}
// @override equals(): boolean -- ?
}
Run Code Online (Sandbox Code Playgroud)
我想使用此类的实例作为映射中的键,如下所示:
const map = new Map<Path, string>();
map.set(new Path(['hello'], ['world'], 'asdf'), 'hwa');
map.set(new Path(['see', 'you'], ['world'], 'asdf'), 'swa');
map.get(new Path(['hello'], ['world'], 'asdf')); // 'hwa'
map.get(new Path(['see', 'you'], ['world'], 'asdf')); // …Run Code Online (Sandbox Code Playgroud) 我目前正在尝试编写一个函数,以十进制返回列表的平均值。
(defun calc-list-average (lst)
(float (/ (apply '+ lst) (length lst))))
Run Code Online (Sandbox Code Playgroud)
当我像这样调用函数时,一切正常:
(defvar *a-lst* '(5 6 1 3 6 7))
(princ (calc-list-average *a-lst*))
Run Code Online (Sandbox Code Playgroud)
但是,当我尝试使用动态生成的列表调用该函数时,我收到错误“给 + 的参数列表被打点(由 WUERFEL-ERGEBNIS 终止)”
(let ((wuerfel-seiten 6) (wuerfel-ergebnis ()))
(loop
(let ((menu-option (get-option)))
(cond ((eql menu-option 1)
(princ "Bitte geben Sie die Anzahl der Wuerfelseiten ein: ")
(setq wuerfel-seiten (read)))
((eql menu-option 2)
(princ "Bitte geben Sie die Anzahl der Wuerfelwuerfe ein: ")
(let ((wuerfel-wuerfe (read)))
(setq wuerfel-ergebnis (get-random-list wuerfel-seiten wuerfel-wuerfe))))
((eql menu-option 3)
(write-line "Wuerfelauswertung") …Run Code Online (Sandbox Code Playgroud)