彿¸ - å¯éè¤ä½¿ç¨çç¨å¼ç¢¼åå¡
ç¨å¼è¨è¨çå¦ä¸ååºæ¬æ¦å¿µæ¯å½æ¸ï¼å®å è¨±ä½ å²å䏿®µç¨å¼ç¢¼ï¼è©²ç¨å¼ç¢¼å¨å®ç¾©çåå¡å §å·è¡å®åä»»åï¼ç¶å¾å¨éè¦æä½¿ç¨ä¸åç°¡çå½ä»¤èª¿ç¨è©²ç¨å¼ç¢¼åå¡ï¼èä¸å¿ 夿¬¡è¼¸å ¥ç¸åçç¨å¼ç¢¼ã 卿¬æä¸ï¼æåå°æ¢ç´¢å½æ¸èå¾çåºæ¬æ¦å¿µï¼ä¾å¦åºæ¬èªæ³ãå¦ä½èª¿ç¨åå®ç¾©å®åãä½ç¨åç¯åè忏ã
| å åç¥èï¼ | åºç¤é»è ¦è¡èªãå° HTML å CSS æåºæ¬èªèãJavaScript çç¬¬ä¸æ¥ã |
|---|---|
| å¸ç¿ç®æ¨ï¼ | äºè§£ JavaScript 彿¸èå¾çåºæ¬æ¦å¿µã |
æå¨åªè½æ¾å°å½æ¸ï¼
å¨ JavaScript 裡ï¼ä½ å°èé½è½çå°å½æ¸ç蹤影ãäºå¯¦ä¸ï¼æåå¨åé¢ç課ç¨ä¸ä¸ç´é½å¨ç¨å½æ¸ï¼åªæ¯æ²ä»éº¼æåèå·²ãå¦ä»æ¯æåè®æå詳細æ¢è¨å½æ¸ä¸¦èªçæ¢ç´¢å®åçèªæ³äºã
幾乿¯ç¶ä½ 使ç¨äºå
å«ä¸å°å°æ¬è â () â ç JavaScritp çµæ§ï¼ä¸¦ä¸æ²æç¨å°è«¸å¦ for è¿´åãwhile è do...while è¿´åæ if...else æè¿°ç常è¦çå
§å»ºèªè¨çµæ§æï¼ä½ å°±æ¯å¨ä½¿ç¨å½æ¸ã
ç覽å¨å §å»ºå½æ¸
å°ç®åçºæ¢ï¼æåå·²å¨èª²ç¨ä¸å¤§é使ç¨äºç覽å¨å §å»ºç彿¸ãä¾å¦ï¼æ¯ç¶æåææ§ä¸åå串æï¼
var myText = "I am a string";
var newString = myText.replace("string", "sausage");
console.log(newString);
// å串ç replace() 彿¸æå
æ¿æä¸æ®µåå串ï¼
// åå峿¿æéå¾çæ°å串
ææ¯æ¯ç¶æåææ§ä¸åé£åæï¼
var myArray = ["I", "love", "chocolate", "frogs"];
var madeAString = myArray.join(" ");
console.log(madeAString);
// é£åç join() 彿¸æå
å°ææé£åå
ç´ åä½µï¼
// å½¢æä¸åæ°å串ï¼ååå³è©²æ°å串
ææ¯æ¯ç¶æåç¢çä¸åäºæ¸ï¼
var myNumber = Math.random();
// random() 彿¸æå
ç¢çä¸å仿¼ 0 å° 1 ä¹é
// çäºæ¸ï¼ååå³è©²æ¸å
â¦â¦æåå ¶å¯¦ç¶å¨ä½¿ç¨å½æ¸ã
å註ï¼è¥æéè¦ï¼ä½ å¯ä»¥ç覽å¨ç JavaScript 主æ§å°ä¸è¼¸å ¥ä»¥ä¸æä»¤ç¢¼ï¼èæ¤éæ°çæéäºåè½ã
JavaScript èªè¨æå¾å¤å §å»ºå½æ¸ï¼è®ä½ ä¸ç¨éè¦å¯«ææç¨å¼ç¢¼å°±è½åå¾å¤äºãäºå¯¦ä¸ï¼å¨ä½ å·è¡ç覽å¨çå §å»ºå½æ¸æï¼ä½ å¼å«å°çæäºç¨å¼ç¢¼ä¸¦ä¸è½ç¨ JavaScript ä¾å¯«ââå¾å¤éç¨®å½æ¸æ¯å¨é¨åå¼å«ç覽å¨èæ¯èªè¨ï¼å¤§å¤æ¯ç± C++ é種ä½é系統èªè¨å¯«æï¼èé JavaScript é種網é網路èªè¨ã
éº»ç ©è¬¹è¨å¨å¿ï¼æäºç覽å¨å §å»ºå½æ¸ä¸æ¯ JavaScript èªè¨æ ¸å¿çä¸é¨ä»½ââæäºè¢«å®ç¾©çºçè¦½å¨ API çä¸é¨ä»½ï¼å®åå·²é è¨èªè¨çºåºç¤ä¾æä¾æ´å¤åè½ï¼å åçç« ç¯è£¡ææ´å¤èªªæï¼ã卿ªä¾ç模çµä¸æåææ´æ·±å ¥æ¢è¨çè¦½å¨ API çç¨æ³ã
彿¸ï¼functionï¼ vs æ¹æ³ï¼methodï¼
卿åç¹¼çºåï¼æä»¶äºéè¦å 鿏 ââæè¡ä¸ä¾èªªï¼ç覽å¨å §å»ºå½æ¸ä¸¦ä¸æ¯å½æ¸ï¼functionï¼ââå®åæ¯æ¹æ³ï¼methodï¼ãéè½èµ·ä¾æé»ä»¤äººçæï¼ä¸é奿å¿ââå¨ä½ ç®åçå¸ç¿é段ï¼ã彿¸ãèãæ¹æ³ãéå ©åè©å½å¤§å¤æåæ¯å¯ä»¥äºæçï¼è³å°å°æåçç®æ¨èè¨ã
éå ©åè©çåå¥å¨æ¹æ³ï¼methodï¼æ¯å®ç¾©å¨ç©ä»¶è£¡ç彿¸ï¼functionï¼ãç覽å¨å §å»ºå½æ¸ï¼æ¹æ³ï¼åè®æ¸ï¼æ¤è被稱ä½å±¬æ§ï¼propertyï¼ï¼è¢«å²åå¨å»ºæ§å¥½çç©ä»¶è£¡ï¼ä»¤ç¨å¼ç¢¼æ§å¶èµ·ä¾æ´ææç乿´ç°¡å®ã
ä½ éä¸éè¦äºè§£ JavaScript ç©ä»¶çå §é¨éä½ââå¨ä¹å¾çæ¨¡çµæåæå¸å°ç©ä»¶å §é¨çææé使¹å¼ï¼ä»¥åå¦ä½åµå»ºä½ èªå·±çç©ä»¶ãæ¤æï¼æååªéè¦éæ¸ æ¹æ³è彿¸ä¹éä»»ä½å¯è½ææ··çå°æ¹ââå¨ä½ ä¸ç¶²æ¥ç¸éæå¸è³æºæå¾å¯è½å ©åè©å½é½æç¢°å°ã
èªè¨å½æ¸
You've also seen a lot of custom functions in the course so far â functions defined in your code, not inside the browser. Anytime you saw a custom name with parentheses straight after it, you were using a custom function. In our random-canvas-circles.html example (see also the full source code) from our loops article, we included a custom draw() function that looked like this:
function draw() {
ctx.clearRect(0, 0, WIDTH, HEIGHT);
for (var i = 0; i < 100; i++) {
ctx.beginPath();
ctx.fillStyle = "rgba(255,0,0,0.5)";
ctx.arc(random(WIDTH), random(HEIGHT), random(50), 0, 2 * Math.PI);
ctx.fill();
}
}
This function draws 100 random circles inside an <canvas> element. Every time we want to do that, we can just invoke the function with this
draw();
rather than having to write all that code out again every time we want to repeat it. And functions can contain whatever code you like â you can even call other functions from inside functions. The above function for example calls the random() function three times, which is defined by the following code:
function random(number) {
return Math.floor(Math.random() * number);
}
We needed this function because the browser's built-in Math.random() function only generates a random decimal number between 0 and 1. We wanted a random whole number between 0 and a specified number.
å¼å«å½æ¸
You are probably clear on this by now, but just in case ... to actually use a function after it has been defined, you've got to run â or invoke â it. This is done by including the name of the function in the code somewhere, followed by parentheses.
function myFunction() {
alert("hello");
}
myFunction();
// å¼å«ä¸æ¬¡å½æ¸
å¿å彿¸
You may see functions defined and invoked in slightly different ways. So far we have just created a function like so:
function myFunction() {
alert("hello");
}
But you can also create a function that doesn't have a name:
function() {
alert('hello');
}
This is called an anonymous function â it has no name! It also won't do anything on its own. You generally use an anonymous function along with an event handler, for example the following would run the code inside the function whenever the associated button is clicked:
var myButton = document.querySelector("button");
myButton.onclick = function () {
alert("hello");
};
The above example would require there to be a <button> element available on the page to select and click. You've already seen this structure a few times throughout the course, and you'll learn more about and see it in use in the next article.
You can also assign an anonymous function to be the value of a variable, for example:
var myGreeting = function () {
alert("hello");
};
This function could now be invoked using:
myGreeting();
This effectively gives the function a name; you can also assign the function to be the value of multiple variables, for example:
var anotherGreeting = function () {
alert("hello");
};
This function could now be invoked using either of
myGreeting();
anotherGreeting();
But this would just be confusing, so don't do it! When creating functions, it is better to just stick to this form:
function myGreeting() {
alert("hello");
}
You will mainly use anonymous functions to just run a load of code in response to an event firing â like a button being clicked â using an event handler. Again, this looks something like this:
myButton.onclick = function () {
alert("hello");
// ééä½ çç¨å¼ç¢¼æ³å¯«å¤é·å°±å¯«å¤é·
};
彿¸åæ¸
Some functions require parameters to be specified when you are invoking them â these are values that need to be included inside the function parentheses, which it needs to do its job properly.
å註ï¼Parameters are sometimes called arguments, properties, or even attributes.
As an example, the browser's built-in Math.random() function doesn't require any parameters. When called, it always returns a random number between 0 and 1:
var myNumber = Math.random();
The browser's built-in string replace() function however needs two parameters â the substring to find in the main string, and the substring to replace that string with:
var myText = "I am a string";
var newString = myText.replace("string", "sausage");
å註ï¼When you need to specify multiple parameters, they are separated by commas.
It should also be noted that sometimes parameters are optional â you don't have to specify them. If you don't, the function will generally adopt some kind of default behavior. As an example, the array join() function's parameter is optional:
var myArray = ["I", "love", "chocolate", "frogs"];
var madeAString = myArray.join(" ");
// åå³ 'I love chocolate frogs'
var madeAString = myArray.join();
// åå³ 'I,love,chocolate,frogs'
If no parameter is included to specify a joining/delimiting character, a comma is used by default.
彿¸ä½ç¨ååè¡çª
Let's talk a bit about scope â a very important concept when dealing with functions. When you create a function, the variables and other things defined inside the function are inside their own separate scope, meaning that they are locked away in their own separate compartments, unreachable from inside other functions or from code outside the functions.
The top level outside all your functions is called the global scope. Values defined in the global scope are accessible from everywhere in the code.
JavaScript is set up like this for various reasons â but mainly because of security and organization. Sometimes you don't want variables to be accessible from everywhere in the code â external scripts that you call in from elsewhere could start to mess with your code and cause problems because they happen to be using the same variable names as other parts of the code, causing conflicts. This might be done maliciously, or just by accident.
For example, say you have an HTML file that is calling in two external JavaScript files, and both of them have a variable and a function defined that use the same name:
<!-- Excerpt from my HTML -->
<script src="first.js"></script>
<script src="second.js"></script>
<script>
greeting();
</script>
// first.js
var name = "Chris";
function greeting() {
alert("Hello " + name + ": welcome to our company.");
}
// second.js
var name = "Zaptec";
function greeting() {
alert("Our company is called " + name + ".");
}
Both functions you want to call are called greeting(), but you can only ever access the second.js file's greeting() function â it is applied to the HTML later on in the source code, so its variable and function overwrite the ones in first.js.
å註ï¼You can see this example running live on GitHub (see also the source code).
Keeping parts of your code locked away in functions avoids such problems, and is considered best practice.
It is a bit like a zoo. The lions, zebras, tigers, and penguins are kept in their own enclosures, and only have access to the things inside their enclosures â in the same manner as the function scopes. If they were able to get into other enclosures, problems would occur. At best, different animals would feel really uncomfortable inside unfamiliar habitats â a lion or tiger would feel terrible inside the penguins' watery, icy domain. At worst, the lions and tigers might try to eat the penguins!

The zoo keeper is like the global scope â he or she has the keys to access every enclosure, to restock food, tend to sick animals, etc.
äºåå¸ç¿ï¼ç©è½ä½ç¨å
Let's look at a real example to demonstrate scoping.
-
First, make a local copy of our function-scope.html example. This contains two functions called
a()andb(), and three variables âx,y, andzâ two of which are defined inside the functions, and one in the global scope. It also contains a third function calledoutput(), which takes a single parameter and outputs it in a paragraph on the page. -
Open the example up in a browser and in your text editor.
-
Open the JavaScript console in your browser developer tools. In the JavaScript console, enter the following command:
jsoutput(x);You should see the value of variable
xoutput to the screen. -
Now try entering the following in your console
jsoutput(y); output(z);Both of these should return an error along the lines of "ReferenceError: y is not defined". Why is that? Because of function scope â
yandzare locked inside thea()andb()functions, sooutput()can't access them when called from the global scope. -
However, what about when it's called from inside another function? Try editing
a()andb()so they look like this:jsfunction a() { var y = 2; output(y); } function b() { var z = 3; output(z); }Save the code and reload it in your browser, then try calling the
a()andb()functions from the JavaScript console:jsa(); b();You should see the
yandzvalues output in the page. This works fine, as theoutput()function is being called inside the other functions â in the same scope as the variables it is printing are defined in, in each case.output()itself is available from anywhere, as it is defined in the global scope. -
Now try updating your code like this:
jsfunction a() { var y = 2; output(x); } function b() { var z = 3; output(x); }Save and reload again, and try this again in your JavaScript console:
jsa(); b();Both the
a()andb()call should output the value of x â 1. These work fine because even though theoutput()calls are not in the same scope asxis defined in,xis a global variable so is available inside all code, everywhere. -
Finally, try updating your code like this:
jsfunction a() { var y = 2; output(z); } function b() { var z = 3; output(y); }Save and reload again, and try this again in your JavaScript console:
jsa(); b();This time the
a()andb()calls will both return that annoying "ReferenceError: z is not defined" error â this is because theoutput()calls and the variables they are trying to print are not defined inside the same function scopes â the variables are effectively invisible to those function calls.
å註ï¼The same scoping rules do not apply to loop (e.g. for() { ... }) and conditional blocks (e.g. if() { ... }) â they look very similar, but they are not the same thing! Take care not to get these confused.
å註ï¼The ReferenceError: "x" is not defined error is one of the most common you'll encounter. If you get this error and you are sure that you have defined the variable in question, check what scope it is in.
彿¸è£¡ç彿¸
Keep in mind that you can call a function from anywhere, even inside another function. This is often used as a way to keep code tidy â if you have a big complex function, it is easier to understand if you break it down into several sub-functions:
function myBigFunction() {
var myValue;
subFunction1();
subFunction2();
subFunction3();
}
function subFunction1() {
console.log(myValue);
}
function subFunction2() {
console.log(myValue);
}
function subFunction3() {
console.log(myValue);
}
Just make sure that the values being used inside the function are properly in scope. The example above would throw an error ReferenceError: myValue is not defined, because although the myValue variable is defined in the same scope as the function calls, it is not defined inside the function definitions â the actual code that is run when the functions are called. To make this work, you'd have to pass the value into the function as a parameter, like this:
function myBigFunction() {
var myValue = 1;
subFunction1(myValue);
subFunction2(myValue);
subFunction3(myValue);
}
function subFunction1(value) {
console.log(value);
}
function subFunction2(value) {
console.log(value);
}
function subFunction3(value) {
console.log(value);
}
çµè«
éç¯æç« æ¢è¨äºå½æ¸èå¾çåºæ¬è§å¿µï¼çºä¸ä¸ç« çå¯¦æ°æ¼ç·´ä»¥åå¸¶ä½ ä¸æ¥æ¥å»ºç«ä½ çèªè¨å½æ¸å¥ å®åºç¤ã
æ´å¤è«ç
- 彿¸è©³ç´°æå â å å«ä¸äºæ¬æçºæåçé²éåè½
- 彿¸åèæä»¶
- é è¨åæ¸ãç®é 彿¸ â é²éæ¦å¿µåèæä»¶