函數是Javascript 中很重要的對象,JS 提供三種方式實現函數。
1. function 關鍵字
1.1 定義function 函數
function student() {
this.name = 'spursy';
this.age = 20;
}
var stu = new student();
console.log(stu instanceof student); // true
console.log(typeof(student)); // function
console.log(typeof(stu)); // object
1.2 自定義匿名類
var stu = new function() {
this.name = 'spursy';
this.age = 20;
};
console.log(typeof(stu)); // object
2. 系統內置函數對象(Function)來構建一個函數
/**
* Demo 1
*/
let str = 'return ' + '` This is ${name}.`';
let fun = new Function('name', str);
var result = fun("Spursy");
console.log(result); // This is Spursy.
/**
* Demo 2
*/
let str = '(name) => ` This is ${name}.`';
let fun = eval.call(null, str);
var result = fun("Spursy");
console.log(result); // This is Spursy.
3. ES6 箭頭函數(arrow function)
var numbers = [1,3,5,7,9];
var result = numbers.map((number) => number * 3);
console.log(result); // [3, 9, 15, 21, 27]
ES6的箭頭函數省略了 function 關鍵字,并在參數后面添加了 ‘=>’.
(async() => {
await result.total3(); // 箭頭函數與async/ await 的結合
})
箭頭函數不綁定this
a. 由于 this 已經在詞法層面完成了綁定,通過 call() 或 apply() 方法調用一個函數時,只是傳入了參數而已,對 this 并沒有什么影響。
b. 在箭頭函數內部使用 var that = this, debug 發現 that 指向為undefined。
var adder = {
base : 1,
add : function(a) {
var f = v => v + this.base;
return f(a);
},
addThruCall: function(a) {
var f = v => v + this.base;
var b = {
base : 2
};
return f.call(b, a);
}
};
console.log(adder.add(1)); // 輸出 2
console.log(adder.addThruCall(1)); // 仍然輸出 2(而不是3 ——譯者注)
function multiply (x, y) {
return x * y;
}
var result = {
value: 3,
total: () =>
{
var that = this; // that 指向undefined
that.value = multiply(that.value, that.value);
}
};
(async() => {
await result.total3();
})