Javascript中静态函数声明和普通函数声明的区别?

Difference between Static function declaration and the normal function declaration in Javascript?

在 javascript 中可以通过多种方式声明一个函数。 其中一种方法是声明一个 class 和内部的静态函数,如下所示。

class className {
 static fucntionName() {
 }
}

另一种声明方式是通过传统 javascript 样式,如下所示。

function functionName() {
}

我想知道使用这两种情况的 advantages/disadvantages。 静态方法是否有任何特定的用例,为什么要声明一个class(我们知道在javascript中不需要实例化class来访问静态函数)。 为什么不直接在all/any用例中使用函数声明的传统方式(上例中的第二种情况)?

我想了解的很详细

如您所知,static 方法可从 class 本身调用。

static 方法可从 class 的 实例 调用,因此您基本上必须先创建一个对象才能访问那个方法。

例如,对于执行 return a+baddNumbers(var a, var b),是否真的有必要浪费内存实例化 class 的对象只是为了添加这 2 个数字?不,您只需要结果,这就是静态的全部意义。

使用第一种样式可以让您将方法分组到特定的 class(想想命名空间之类的东西)。也许您可以定义 class 类,例如 MathString,它们都具有 add 方法,但实现方式不同。单独调用 add() 会令人困惑,但 Math.add()String.add() 不会。

export 风格,另一方面,做了完全不同的事情。它允许您使用来自另一个模块的功能。

想想这个:

first_module.js

function cube(var x) {
    return x * x * x;
}

second_module.js

import { cube } from 'first_module'; // <-- ERROR
alert( cube(3) ); // <-- Undefined function

但是,如果您这样声明 first_module:

export function cube(var x) {
    return x * x * x;
}

那么second_module就可以了。

What is a static function?

在 class 中声明静态函数会创建一个 class 级别的函数,该函数的实例无法调用该函数。 Object.assign 函数就是一个例子。静态函数通常用于构建对定义类型的实例进行操作的函数。

I would like to know the advantages/disadvantages of using either of the cases.

苹果和橘子。 class 不必导出,模块也不必是 class。它们不是一回事,尽管导出的模块可以是 class.

Is there any specific use cases for the static methods

当您希望 class 提供某些功能时,但这并不是特定于 class 的单个实例的功能。喜欢var c = Point.interpolate(a, b, .5);
static interpolate 函数不属于它正在运行的任何点。在提供此功能的 class 上将此函数定义为静态更合适 (interpolating points).

we know that in javascript there is no need to instantiate the class in order to access the static function

这是静态函数的定义,您无需实例化 class 即可调用它。这不是 JS 特有的东西。

Why not just use the traditional way (the second case in the above example) of function declaration in all/any use case

因为在我开始时,class 和模块不一定是同一回事。而写

是nicer/cleaner
class Foo{
    ...
    static fn(){...}
}

class Foo {
    ...
}

Foo.fn = function(){...};

虽然到头来,两者都只比

function Foo(){...}
Foo.fn = function(){};
// + Foo.prototype stuff

但是 class 语法更清晰。更易于阅读和理解,即使您只是浏览这段代码。

静态方法只能在 class 中调用,并且对实用函数很有用,比如处理传入的参数变量,或设置常量,(或 Object.assign前面提到过)每次都必须这样做,然后再传递给 class 的实例化,以避免不必要地使用内存,正如之前的评论员所指出的那样。

清理完所有内容后,您可以导出函数的其余部分以在代码中的其他地方进行实例化,其中参数将被清理 up/constants 设置,每次使用 class,你的实例化可以专注于动态的东西。