在學Function前,先對 Object 與 primitive 做個簡單的比較
primitive
var a = 10;
var b = a;
a = 15;
console.log(a, b);
// output : 10, 15
// a 最後不等於 b 是因為 primitive 為變數本身被賦值
primitive and object
var obj1 = {
name : 'eric',
age : 19
}
var obj2 = obj1; //object
var testPrimitive = obj1.age; // primitive
obj1.age = 20;
console.log(obj1.age, obj2.age, testPrimitive);
// 20, 20, 19
// obj1 & obj2 都指向同記憶體,而 testPrimitive 本身被賦值
將函數作為參數傳遞給另一個函數
var years = [1998, 1996, 2005];
// fn : function
function arrayCal(arr, fn){
var response = [];
for(var i = 0; i < arr.length; i++){
response.push(fn(arr[i]));
}
return response;
}
function calculateAge(age){
return 2020 - age;
}
function isFullAge(el){
return el >= 20;
}
var ages = arrayCal(years, calculateAge);
console.log(ages);
// output : [22, 24, 15]
var checkIsFull = arrayCal(ages, isFullAge);
console.log(checkIsFull);
// output : [true, true, false]
function 做為 function 的回傳值
function interview(job){
if(job === 'Frontend'){
return function(name){
console.log('Hi, ' + name + '!');
console.log('Is JavaScript your main language?');
}
}else if(job === 'Backend'){
return function(name){
console.log('Good morning, ' + name + '!');
console.log('Can you please explain what MVC is?');
}
}else{
return function(name){
console.log('Sorry, ' + name + '.');
console.log('We are not looking for a ' + job);
}
}
}
// assign the function to variable and call it
var frontEndInterview = interview('Frontend');
frontEndInterview('sui');
// output : Hi, sui!
// output : Is JavaScript your main language?
var backEndInterview = interview('Backend');
backEndInterview('ken');
// output : Hi, ken!
// output : Can you please explain what MVC is?
// without assign to variable
interview('Teacher')('jay')
// output : Sorry, jay.
// output : We are not looking for a Teacher
除了常見的 Function Statement 和 Function Expression
還有一種寫法 IIFEs (Immediately Invoked Functions Expressions)
也就是立即調用且不需呼叫
不帶參數
(function() {
var n = Math.random() * 10;
console.log(n);
console.log(n > 5);
})();
// output : 3.362294415982372
// output : false
帶參數
(function(n) {
console.log(n);
console.log(n > 5);
})(6);
// output : 6
// output : true
都是實作,雖然蠻基礎的,但感覺又進步了一點
課程 : https://www.udemy.com/course/the-complete-javascript-course/
來源 : https://pjchender.blogspot.com/2016/05/javascriptiifesimmediately-invoked.html