箭頭函式
Node.js 箭頭函式
變數 | 說明 |
---|---|
Function.call() | 執行函式,並改變函式中的 this 物件為指定變數,函式參數依序帶入 |
Function.apply() | 執行函式,並改變函式中的 this 物件為指定變數,函式參數為陣列 |
Function.bind() | 建立函式,並改變函式中的 this 物件為指定變數,下次呼叫時會使用改變過後的 this 物件執行 |
call
與 apply
皆是直接執行函式,只是參數傳入方式不同bind
會綁定 this
並回傳已綁定函式,在之後呼叫執行
function add(a, b) {
return a + b;
}
// call
console.log(add.call(null, 1, 2)); // 3
console.log(add.call(null, 1, 4)); // 5
// apply
console.log(add.apply(null, [1, 2])); // 3
console.log(add.apply(null, [1, 4])); // 5
// bind
let add1 = add.bind(null, 1);
console.log(add1(2)); // 3
console.log(add1(4)); // 5
傳入參數第一個是要改變的 this 變數,後面是函式需要用的參數,依序列出
Function.call(要改變的this, 參數1, 參數2...)
傳入參數只有 2 個,函式用的參數用陣列包起來傳入
Function.apply(要改變的this, [參數1, 參數2...])
Function.bind(要改變的this, 參數1, 參數2...)
在傳入參數後方加入 =
即可設定預設值
const SayHi = (name, age = 17) => {
console.log(`My name is "${name}", and my age is "${age}"`);
}
// My name is "Kay", and my age is "19"
SayHi('Kay', 19);
// My name is "Jay", and my age is "17"
SayHi('Jay');
舊的設定預設值方式
const SayHi = (name, age ) => {
age = age || 17;
console.log(`My name is "${name}", and my age is "${age}"`);
}
// My name is "Kay", and my age is "19"
SayHi('Kay', 19);
// My name is "Jay", and my age is "17"
SayHi('Jay');
new
會讓 this
指向到新建立的物件實體
function Animal(name) {
this.name = name;
this.walk = () => {
console.log(`[Animal] ${this.name} walking`);
}
}
let myAnimal = new Animal('Kay');
// Animal { name: 'Kay', walk: [Function (anonymous)] }
console.log(myAnimal);
用函式縮寫的方式沒辦法順利 new
物件實例
let Animal = (name) => {
this.name = name;
this.walk = () => {
console.log(`[Animal] ${this.name} walking`);
}
}
// TypeError: Animal is not a constructor
let myAnimal = new Animal('Kay');
Node.js 箭頭函式