30 Days of Mootools 1.2 Tutorials - Day 4 - Functionshttp://www.consideropen.com/blog/2008/0 ... functions/原作者: Troy
翻譯: Jui-Yu Tsai
Functions and Mootools 1.2Welcome to day 4 of the 30 Days of Mootools. If you haven’t already, go check out the previous Mootools Tutorials in the series. Today we’re taking a step back from the Mootools to go over the basics of functions in javascript.
歡迎來到第四天的Mootools教學. 如果有跳過任何之前Mootools的教學, 不要忘記回去補完之前的教學歐. 這次教學我們將專注於javascript的基本函數(function).
Keeping with the Mootools theme however, you should be aware of where to place functions for use with Mootools. Previously we’ve been placing all of our example code within the domready function. When dealing with functions you want to place them outside of the domready loop. Functions aren’t executed until you call them from within the domready.
跟隨著Mootools的作風, 你應該要了解函數在Mootools的放置位置. 在之前的教學, 我們把範例的程式碼放在domready函數裡面. 但在處裡這些函數時, 我們應該把這些函數放在domready函數外. 函數本身將不會自行執行, 而是要等到他們在domready函數裡被呼叫.
Generally it’s a good idea to try and keep as much of your function code outside of the page body all together and call it in through a javascript include. When just monkeying around with code though, I find it easier just to keep everything on the same page. We’re using the following convention for these tutorials:
一般而言, 建議把javascript的程式碼和一般頁面的程式碼區分開來. 但為了便利教學, 整個教學過程將把javascript的程式碼和一般頁面程式碼放在同一頁面. 整個教學將利用以下樣版:
- Code: Select all
<script type="text/javascript">
/*
* 函數定義區
* Function definitions go here
*/
window.addEvent('domready', function() {
/*
* 呼叫函數區
*Calls to functions go here
*/
});
</script>
All the examples follow this format, which results in the function being executed when the page loads. They also all have example buttons beneath them which you can press to see the results. This is accomplished through the using Mootools event handlers which we’ll be talking about tomorrow.
將來的範例也將跟隨以上的風格. 函數的結果將在頁面讀取時進行. 範例也提供了範例按鈕提供實際的操作(此功能尚未在本翻譯文章中提供). 這些完全是明天要教的用Mootools事件處理器(event handlers)完成的.
The BasicsThere are a few ways to define functions in javascript—since we’re focusing on Mootools we’ll be using their preferred methodology. The example below is about as basic as a function can get. We declare a variable named simple_function and define it as a function:
Javascript提供了幾種不同定義函數(function)的方法 - 既然我們專注的是Mootools, 我們將用Mootools喜好的方法. 以下的範例是最基本的範例. 此範例將定義一個變數, 叫做simple_function, 並將其定義為一函數.
- Code: Select all
var simple_function = function(){
Then we add an alert to be run when the function is called:
然後在函數呼叫時啟動上警示視窗(alert).
- Code: Select all
alert('This is a simple function');
Finally, we close the function definition with a closing curly bracket:
最後將函數定義用括號關起.
- Code: Select all
}
This closing bracket is one of the easiest things to overlook, and can often times be an incredible pain to track down—it’s a good idea to be mildly obsessive about double checking the closing of your function definitions.
結束括號是很簡單的一個動作, 但也常常被遺忘, 一但這種事發生, 整個除蟲的過程將會很不好玩.
It’s all rolled together in the example below. After declaring the function, we’re adding a call to the function to the domready event that will execute on page load. Press the button beneath the example to see the result of calling simple_function(); .
以下範例是結合上述的教學. 在定義完函數之後, 我們在domready事件內呼叫之前定義的含數.
- Code: Select all
//Define simple_function as a function
var simple_function = function(){
alert('This is a simple function');
}
window.addEvent('domready', function() {
//Call simple_function when the dom(page) is ready
simple_function();
});
Single ParameterWhile having a chunk of code you can easily call from anywhere is useful, it’s even more useful when you can pass it parameters (information) to work with. To use parameters with functions, you need to add a variable name in the parenthesis after function like so:
可以從程式碼中任意的呼叫另外定義的一推程式碼是非常便利的, 如果你能代入參數(parameters)將會變得更有用. 想要使用變數, 你必須在函數(function)的括號內加入變數的名稱.
- Code: Select all
var name_of_function = function(name_of_the_parameter){
/*function code goes here*/
}
Once you’re done, the variable is available inside the function for use. While you can name a parameter pretty much anything you want, it’s a good idea to make your parameter names as descriptive as possible. So for instance, if you were passing a parameter that held the name of a town, calling the parameter town_name would be preferable to something more vague (like user_input).
一但你代入參數, 此參數將可以在函數內部被使用. 你可以任意的對參數命名, 但一個有意義的參數將會讓整個程式碼更簡單被理解. 舉例來說, 如果你要代入一個代表城鎮名的參數, 參數"城鎮名稱(town_name)"將比模糊的"使用者輸入(user_input)"來的容易懂.
In the example below, we’re defining a function that takes a single parameter (called parameter) and sends out an alert containing the parameter. Note that while the first part of the message is surrounded by single quotes, the parameter is not. When you want to use parameters in combination with hardcoded strings, you need to join them together with the + operator as shown below:
下列的範例我們定一了一個可以代入單一參數(parameter)的函數(function), 並且在呼叫此函數時啟動警示視窗來顯示參數內容. 注意第一部分的內容是被單引號括住的, 但參數部分並不需要. 當你要一起使用參數和特定文字(hardcoded strings)時, 你將需要用+運算符號來做連結.
- Code: Select all
var single_parameter_function = function(parameter){
alert('the parameter is : ' + parameter);
}
window.addEvent('domready', function(){
single_parameter_function('this is a parameter');
});
Multiple ParametersJavascript doesn’t limit the amount of parameters you can define for a function. It’s generally a good idea to try and keep the number of parameters you pass to a function to a minimum for readability’s sake. Multiple parameters in a function definition are separated by commas, and otherwise behave exactly the same as a single parameter function. The example function below takes two numbers, and places their sum into the variable third_number like so:
Javascript函數沒有參數數目的限制. 但適當的使用參數並且控制在最少的數量將變於程式碼的閱讀. 多個參數將以逗號來做區隔, 其他部分跟單一參數沒有什麼不同. 以下的範例將代入兩個數字, 並把兩數字加總指派到另一個變數.
- Code: Select all
var third_number = first_number + second_number;
Then the + operator is used in a slightly different fashion to join the results together into a text string:
+ 運算符號在此將產生不同於連結字串的效果.
- Code: Select all
alert(first_number + " plus " + second_number + " equals " + third_number);
While this may seem confusing at first, it’s actually pretty straightforward. If you use + between numbers, you’re adding them together. If you use + between any combination of numbers and strings you’re joining all the input into a single string.
在此, 你可能對+運算符號感到疑惑, 但其實不難理解其中的奧秘. 如果在兩數字中使用+運算符號, 此功能將會是加總. 如果在其中一方為字串, 像是數字和字串, 結果將是字串的連結.
- Code: Select all
var two_parameter_function = function(first_number, second_number){
//Get the sum of first_number and second_number
var third_number = first_number + second_number;
//Display the Results
alert(first_number + " plus " + second_number + " equals " + third_number);
}
window.addEvent('domready', function(){
two_parameter_function(10, 5);
});
Returning a ValueDisplaying the results of a function in an alert can be helpful, but sometimes you’ll want to take the result and use it somewhere else. To accomplish this you need to make use of return within the function. The example below functions pretty much the same as the previous example, except instead of sending out an alert, the script returns the sum of the two numbers here :
以警示視窗顯示結果是很方便的, 但有時你將需要將函數結果應用在其他的程式碼. 要使用函數中的結果在其他地方使用, 你必須在函數中使用傳回(return)語法. 以下範例跟之前的範例大同小異, 只是用傳回兩數字加總來取代警示視窗訊息.
- Code: Select all
return third_number;
You’ll notice that we’re doing more in the domready as well. In order to display this value, we’re assigning the functions return value to a parameter named return_value and then displaying an alert.
你可能也注意到我們在domready函數裡也動了手腳. 為了要顯示傳回的數值, 我們用變數(return_value)來接函數傳回的值, 並用警示視窗來顯示.
- Code: Select all
var two_parameter_returning_function = function(first_number, second_number){
var third_number = first_number + second_number;
return third_number;
}
window.addEvent('domready', function(){
var return_value = two_parameter_returning_function(10, 5);
alert("return value is : " + return_value);
});
Functions as ParametersIf you look at the Mootools domready code we’re wrapping things in, you’ll notice that you’re passing a function as a parameter :
仔細探查Mootools domready函數的程式碼部分, 你將會察覺我們把一整個函數(function)代入參數(parameter).
- Code: Select all
window.addEvent('domready', function(){
/*code*/
});
A function that is passed as a parameter like this is referred to as an anonymous function:
像上述程式碼把函數以參數方式代入稱之為"匿名函數(anonymous function)":
- Code: Select all
function(){
/*code*/
}
In the Day 1 comments Boomstix pointed out an alternate method for using the domready without using anonymous functions. Doing so would look something like this :
在第一天的教學, Boomstix的回應中指出有另一種可以不使用匿名函數使用domready的方式. 這種方式將在下列程式碼中呈現:
- Code: Select all
//Build the function to be called on domready
var domready_function(){
/*code*/
}
//Assign the function to the domready event
window.addEvent('domready', domready_function);
I’m not aware of any significant difference between the performance or functionality of the two methods, so I believe this is essentially a stylistic choice. We’re going to be sticking with our method for now, but if anyone out there knows otherwise please let us know.
目前看來, 不論在功能上或效能上, Boomstix的方式並無不同, 原作者相信這只是個人寫程式風格, 所以日後的教學會延用之前的風格, 如果真的有功能或效果上的不同, 請讓我們知道.
ExamplesTo whet your appetite for tomorrow (and make up for the lack of mootools today), I present a somewhat pointless function to let you change the background color of this page on the fly :
為了提升你學習的慾望(和彌補今天Mootools教學部分不多), 以下將提供一個無關緊要但華麗的範例來讓你改變頁面背景顏色.
- Code: Select all
var changeColor = function(){
//Use get to retrieve the color
//values from the text boxes
//( http://docs.mootools.net/Element/Element#Element:get )
var red = $('red').get('value');
var green = $('green').get('value');
var blue = $('blue').get('value');
//Make sure everything is an integer
//( http://docs.mootools.net/Native/Number#Number:toInt )
red = red.toInt();
green = green.toInt();
blue = blue.toInt();
//Make sure each number is between
//1 and 255, rounding if needed
//( http://docs.mootools.net/Native/Number#Number:limit )
red = red.limit(1, 255);
green = green.limit(1, 255);
blue = blue.limit(1, 255);
//Get the Hex Code
//( http://docs.mootools.net/Native/Array/#Array:rgbToHex )
var color = [red, green, blue].rgbToHex();
//Set the Background color of the page
//( http://docs.mootools.net/Element/Element.Style#Element:setStyle )
$('body_wrap').setStyle('background', color);
}
var resetColor = function(){
//Reset the background color to white
//( http://docs.mootools.net/Element/Element.Style#Element:setStyle )
$('body_wrap').setStyle('background', '#fff');
}
window.addEvent('domready', function(){
//Add click events to the buttons (more on this tommorrow)
//( http://docs.mootools.net/Element/Element.Event#Element:addEvent )
$('change').addEvent('click', changeColor);
$('reset').addEvent('click', resetColor);
});
To Learn More…Download a zip with everything you need to get startedIncluding the Mootools 1.2 core, an external javascript file, a simple html page and a css file.
此檔案由原文章出處提供. 此檔案幫含了Mootools 1.2 core, 外加的javascript和css檔案, 和以上的範例.
More on Javascript Functions
Quirksmode on Javascript FunctionsI’m a little light on good resources for on Javascript functions, if anyone knows of good ones please send them my way
如果你有任何其他更好的Javascript函數資源, 請回應與我們分享.
Example Documentation
Utilities/DomReadyNumber.toInt()Number.limit()Array.rgbToHex()Element.setStyle()Element.addEvent()Tomorrow’s Mootools 1.2 Tutorial - Events
Check in tomorrow for Day 5 - Events.
別忘了下次的教學 - 事件