问题描述
有很多方法可以在 javascript 中声明一个函数.其中一种方法是声明一个类,其中的静态函数如下所示.
There are many ways one can declare a function in javascript. One of the ways is declaring a class and a static function inside is as showed below.
class className {
static fucntionName() {
}
}
另一种声明方式是通过传统的javascript样式,如下所示.
another way of is declaring is through the tradition javascript style as showed below.
function functionName() {
}
我想知道使用这两种情况的优缺点.静态方法是否有任何特定用例,为什么要声明一个类(我们知道在 javascript 中不需要实例化该类来访问静态函数).为什么不在所有/任何用例中都使用传统的函数声明方式(上例中的第二种情况)?
I would like to know the advantages/disadvantages of using either of the cases. Is there any specific use cases for the static methods, why declare a class(we know that in javascript there is no need to instantiate the class in order to access the static function). Why not just use the traditional way (the second case in the above example) of function declaration in all/any use case?
我想详细了解一下.
推荐答案
如你所知,static
方法可以从类本身调用.
A static
method is callable from the class itself, as you already know.
非静态
方法可以从类的实例调用,因此您基本上必须先创建一个对象才能访问该方法.
A non-static
method is callable from an instance of the class, so you basically have to create an object before being able to access that method.
例如,对于一个 addNumbers(var a, var b)
它确实 return a+b
,是否真的有必要浪费内存来实例化类的对象只是添加这两个数字?不,你只需要结果,这就是静态的全部意义.
For example, for a addNumbers(var a, var b)
which does return a+b
, is it really necessary to waste memory instantiating an object of the class just to add those 2 numbers? No, you just need the result and that's the whole point of having static.
使用第一种样式允许您将特定类中的方法分组(想想命名空间之类的东西).也许您可以定义像 Math
和 String
这样的类,它们都有 add
方法,但以不同的方式实现.单独调用 add()
会令人困惑,但 Math.add()
和 String.add()
不会.
Using the first style allows you to group methods in a particular class (think of something like namespaces). Maybe you can define classes like Math
and String
, which both have the add
method but implemented in a different way. Calling add()
by itself would be confusing, but Math.add()
and String.add()
are not.
export
风格,另一方面,做了完全不同的事情.它允许您使用来自另一个模块的函数.
The export
style, on the other way, does a completely different thing. It allows you to use functions from another module.
想一想:
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:
But, if you declare first_module this way:
export function cube(var x) {
return x * x * x;
}
那么 second_module 就可以正常工作了.
Then second_module will work fine.
这篇关于Javascript中静态函数声明和普通函数声明的区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!