JavaScript実行環境とスコープについて話してください.
14796 ワード
<html>
<head lang="en">
<meta charset="UTF-8">
<title> title>
head>
<body>
<script type="text/javascript">
var color = "blue";
function changeColor(){
if (color === "blue"){
color = "green";
} else {
color = "blue";
}
}
changeColor();
console.log("Color is now " + color);//green
script>
body>
html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title> title>
head>
<body>
<script type="text/javascript">
var color = "blue";
function changeColor(){
var anotherColor = "green";
function swapColors(){
var tempColor = anotherColor;
anotherColor = color;
color =tempColor;
// color、anotherColor tempColor
}
swapColors();
// color、anotherColor
}
changeColor();
console.log("Color is now " + color);//green
// color
script>
body>
html>
次のステートメントにフローが入ると、スコープは延長されます.*try-catch文のcatchブロック*with文
これらのステートメントは、コード実行後に削除される変数オブジェクトを、フィールドの先頭に一時的に追加します.
<html>
<head lang="en">
<meta charset="UTF-8">
<title> title>
head>
<body>
<script type="text/javascript">
function buildUrl(){
var qs = "?debug=true";
with (location){
var url = href + qs;
}
return url;
}
console.log(buildUrl());
script>
body>
html>
2ブロックレベルのスコープがない
if (true){
var color = "blue";
}
console.log(color); //"blue"
for (var i=0; i < 10; i++){
doSomething(i);
}
alert(i);//10
2.1宣言変数
<html>
<head lang="en">
<meta charset="UTF-8">
<title> , title>
head>
<body>
<script type="text/javascript">
function add(num1, num2){
var sum = num1 + num2;
return sum;
}
console.log(add(10,20));//30
console.log(sum);//
script>
body>
html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title> ( var), title>
head>
<body>
<script type="text/javascript">
function add(num1, num2){
sum = num1 + num2;
return sum;
}
console.log(add(10,20));//30
console.log(sum);//30( )
script>
body>
html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title> title>
head>
<body>
<script type="text/javascript">
var color = "blue";
function getColor(){
return color;
}
console.log(getColor());//blue
script>
body>
html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title> , title>
head>
<body>
<script type="text/javascript">
var color = "blue";
function getColor(){
var color = "green";
return color;
}
console.log(getColor());//green
script>
body>
html>