Đang chuẩn bị nút TẢI XUỐNG, xin hãy chờ
Tải xuống
Bằng cách này, chúng ta có thể tái sử dụng một phần dữ liệu mà không cần phải nhớ những gì giá trị thực tế của nó, tất cả chúng ta phải làm là nhớ một tên biến. Trong JavaScript, chúng ta tạo ra một biến bằng cách sử dụng từ khóa var và quy định cụ thể tên chúng tôi muốn sử dụng | 50 Simply JavaScript The name that follows the function keyword is the name that you want to give your function function names have the same restrictions as variable names . This is the name you ll call whenever you want your program to run the code inside the function. The name must be followed by round brackets they re empty in this instance but as you ll see in the next section this will not always be the case. In the example above we created a new function called warning so whenever we make a call to this function the statements inside the function will be executed causing an alert box to appear displaying the text This is your final warning. As in the function declaration above round brackets must appear immediately after the function name in a function call warning These brackets serve two purposes they tell the program that you want to execute the function and they contain the data also known as arguments that you want to pass to the function.6 Not every function has to have arguments passed to it but you always have to use the brackets in a function call. Arguments Passing Data to a Function If you look at the ways we used the alert function on previous pages you ll notice that we always inserted a string between the brackets of the function call alert Insert and play The string Insert and play is actually an argument that we re passing to the alert function the alert is designed to take that argument and display it in the browser s alert box. Functions can be designed to take as many arguments as you want and those arguments don t have to be strings they can be any sort of data that you can create in JavaScript. 6 Some people like to call these parameters. Some people also like to eat sheep s brains. Simply JavaScript www.sitepoint.com Programming with JavaScript 51 When you define your function you can provide names for the arguments that are to be passed to it. These are included in the round brackets immediately after the function name with a comma .