10. 問題
var scope = ‘global’;
var f = function() {
console.log(scope); // (1)
var scope = ‘local’;
console.log(scope); // (2)
}
f();
● (1) で出力されるのは?
a. global
b. local
c. 上記以外
● (2) で出力されるのは?
a. global
b. local
c. 上記以外
11. 問題 (答え)
var scope = ‘global’;
var f = function() {
console.log(scope); // (1)
var scope = ‘local’;
console.log(scope); // (2)
}
f();
● (1) で出力されるのは?
a. global
b. local
c. 上記以外
● (2) で出力されるのは?
a. global
b. local
c. 上記以外
12. 巻き上げ
var scope = ‘global’;
var f = function() {
console.log(scope); // undefined
var scope = ‘local’;
console.log(scope); // local
}
f();
var scope = ‘global’;
var f = function() {
var scope;
console.log(scope); // undefined
scope = ‘local’;
console.log(scope); // local
}
f();
=
18. 関数の定義方法は3つある
var f = function(x) {
return x * x;
};
console.log(f(2)); // 4
function square(x) {
return x * x;
}
console.log(square(2)); // 4
関数定義式
(無名)
関数宣言文
関数定義式
(名前付き)
var f = function square(x) {
return x * x;
};
console.log(f(2)); // 4
console.log(square(2)); // エラー
19. 3 つの差異がある
● スタックトレース
● if や while の中での定義
● 巻き上げ
20. スタックトレース(1 / 2)
var f = function() {
throw new Error();
};
f();
function test() {
throw new Error();
}
test();
関数定義式
(無名)
関数宣言文
関数定義式
(名前付き)
var f = function test() {
throw new Error();
};
f();
21. スタックトレース(2 / 2)
Error
at f (/Users/teloo/test.js:2:9)
at Object.<anonymous> (/Users/teloo/test.js:5:1)
at Module._compile (module.js:456:26)
...
Error
at test (/Users/teloo/test.js:2:9)
at Object.<anonymous> (/Users/teloo/test.js:5:1)
at Module._compile (module.js:456:26)
...
22. if や while の中での定義
if (true) {
var f = function(x) {
return x * x;
};
console.log(f(2)); // 4
}
if (true) {
function square(x) {
return x * x;
}
console.log(square(2)); // 4
}
// IE11, Firefox, Chrome, Node.js
で確認したところ動作した
// 仕様的にはしてはいけないらしい
関数定義式
(無名)
関数宣言文
関数定義式
(名前付き)
if (true) {
var f = function square(x) {
return x * x;
};
console.log(f(2)); // 4
}
23. 巻き上げ (1 / 2)
// TypeError: undefined is not
a function
console.log(f(2));
var f = function(x) {
return x * x;
};
console.log(square(2)); // 4
function square(x) {
return x * x;
}
関数定義式
(無名)
関数宣言文
関数定義式
(名前付き)
// TypeError: undefined is not a
function
console.log(f(2));
var f = function square(x) {
return x * x;
};
24. 巻き上げ (2 / 2)
var f;
// TypeError: undefined is not
a function
console.log(f(2));
f = function(x) {
return x * x;
};
function square(x) {
return x * x;
}
console.log(square(2)); // 4
関数定義式
(無名)
関数宣言文
関数定義式
(名前付き)
var f;
// TypeError: undefined is not a
function
console.log(f(2));
f = function square(x) {
return x * x;
};