码迷,mamicode.com
首页 > Web开发 > 详细

JS - Functions

时间:2016-07-04 22:16:49      阅读:169      评论:0      收藏:0      [点我收藏+]

标签:

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

标签:

原文地址:http://www.cnblogs.com/elewei/p/5641767.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!