不确定javascript中的函数是否是我们在其他编程语言中所称的methods,在其他编程语言中,languages.Methods是否可以在access-specifier之后指定它们的结果,例如,在C#中,我会这样做
//method to return int
private int myinteger(){
int a=0;
return a;
}
//method to return string
private string mystring(){
string b="myreturn";
return b;
}我只是不知道如何使用javascript函数,您认为您可以帮助我做一个示例吗?非常感谢:)
发布于 2021-03-25 07:14:21
您不能用javascript来完成这个任务,但是仍然有两个解决方案:
发布于 2021-03-25 07:17:59
您不需要在data types中提供javascript。functions非常类似,您只需用function关键字启动它。
另外,我们需要使用const或let启动变量。
我使用下面的console.log(myinteger());记录浏览器控制台中myinteger()函数的值。(类似于c++的cout)
//method to return int
function myinteger() {
const a = 0;
return a;
}
//method to return string
function mystring() {
const b = "myreturn";
return b;
}
console.log(myinteger());
console.log(mystring());
如果您想使用javascript,但仍然希望分配数据类型和更多的东西,那么您可以使用微软的TypeScript。
发布于 2021-03-25 10:14:25
Javascript有值类型(而不是变量)
因此,可以将变量定义为
var name = "Hamond";要知道它的类型,您必须使用typeof
typeof name; // "string"附带注意:您可以使用let或const而不是var,但让它在另一时间使用。
所以javascript中的变量没有类型,值有。您可以使用typescript添加静态类型
var name: string = "Hamond";在开发时,如果您想编辑name并将其错误地处理为非string类型,您将立即收到一个错误警告。
name = 3; // error
name - 4; // error
// and so forth because `name` is of `string` type因此,这种类型检查是在author或dev时完成的,您不必等到运行时才得到错误。
为什么要谈论变量和值?
因为Javascript函数可以返回任何值(即使返回一个变量,如果它是标量值,则返回它的值;如果它是对象类型,则返回它的引用)
因此,定义一个函数如下所示:
function doSomething(){
return 33;
}注:
undefined)用typescript
function doSomething(): number{
return 33;
}在开发/写入时解决键入问题
关于function和method:我认为开发人员在很多时候都会交替使用这些术语,但是在javascript中,我们只有function,甚至在javascript类中定义的函数也只是一个function。当method在某个类中定义时,人们喜欢它的名称。
参考资料:
https://stackoverflow.com/questions/66794655
复制相似问题