Day 25:不是多了塊魚 —— 立即函數的應用整理
PreviousDay 24:函數呼叫 (Function Invocation) 與立即函數 (Self-Invoking Functions)NextDay 26:程式界的哈姆雷特 —— Pass by value, or Pass by reference?
Last updated
Was this helpful?
Was this helpful?
var temp = 10 + 5;
console.log("Answer is " + temp);
// 執行其他的任務
otherMission();
function otherMission(){
console.log(temp); // temp 是全域變數,仍然存在
}Answer is 15
15(function (){
var temp = 10 + 5;
console.log("Answer is " + temp);
})();
// 執行其他的任務
otherMission();
function otherMission(){
console.log(temp); // temp 不存在於此作用域
}Answer is 15
Uncaught ReferenceError: temp is not definedfunction execOneTime(){
var temp = 10 + 5;
console.log("Answer is " + temp);
}
execOneTime();
// 執行其他的任務
otherMission();
function otherMission(){
console.log(temp); // temp 不存在於此作用域
}var student = {};
student.score = Math.random();
console.log(student.score); // 0.7779381225655557var student = {
score: (function (){ return Math.random(); })()
};
console.log(student.score); // 0.7779381225655557var text = '{ "name":"John", "age":"function () {return 30;}"}';
var person = JSON.parse(text);
console.log(person); // {name: "John", age: "function () {return 30;}"}
console.log(typeof person.age); // "string"
var getAge = eval("(" + person.age + ")");
console.log(getAge); // ƒ () {return 30;}
console.log(getAge()); // 30var add = (function () {
var counter = 0;
return function () {return counter += 1;}
})();
console.log(add);
console.log(add());
console.log(add());
console.log(add());
console.log(counter);ƒ () {return counter += 1;}
1
2
3
Uncaught ReferenceError: counter is not definedjavascript:(function() { function R(a){ona = "on"+a; if(window.addEventListener) window.addEventListener(a, function (e) { for(var n=e.originalTarget; n; n=n.parentNode) n[ona]=null; }, true); window[ona]=null; document[ona]=null; if(document.body) document.body[ona]=null; } R("contextmenu"); R("click"); R("mousedown"); R("mouseup"); R("selectstart");})()