JS - Functions

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了JS - Functions相关的知识,希望对你有一定的参考价值。

Introduction Functions

A function takes in inputs, does something with them, and produces an output.

 1 // This is what a function looks like:
 2 
 3 var divideByThree = function (number) {
 4     var val = number / 3;
 5     console.log(val);
 6 };
 7 
 8 // On line 12, we call the function by name
 9 // Here, it is called ‘dividebythree‘
10 // We tell the computer what the number input is (i.e. 6)
11 // The computer then runs the code inside the function!
12 divideByThree(10);

 

  1. First we declare a function using var, and then give it a name dividByThree. The name should begin with a lowercase letter and the convention is to use lowerCamelCase where each word (except the first) begins with a capital letter.
  2. Then we use the function keyword to tell the computer that you are making a function
  3. The code in the parentheses is called a parameter. It‘s a placeholder word that we give a specific value when we call the function. Click "Stuck? Get a hint!" for more.
  4. Then write your block of reusable code between }. Every line of code in this block must end with a ;.

 

Defining Functions

function square(number) {
  return number * number;
}

 

  • the name of the funciton
  • A list of arguments to the function, enclosed in parentheses and separated by commas.
  • The javascript statements that define the function, enclosed in curly brackets, { };

 

Function Expressions

Such a function can be anonymous; it does not have to have a name.

var square = function(number) { return number * number };
var x = square(4) // x gets the value 16

 

 

 

Scope(global vs local)

Variables defined outside a function are accessible anywhere once they have been declared. They are calledglobal variables and their scope is global.

Variables defined inside a function are local variables. They cannot be accessed outside of that function.

 

以上是关于JS - Functions的主要内容,如果未能解决你的问题,请参考以下文章

IBM Cloud Functions 和 Node.js:如何获取日本时间?

谷歌浏览器调试jsp 引入代码片段,如何调试代码片段中的js

声明单独的 Firebase Cloud Functions 并仍然使用 Express.js

VSCode自定义代码片段——JS中的面向对象编程

VSCode自定义代码片段9——JS中的面向对象编程

来自 Google Cloud Functions Node.js 的 HTTP POST?