Function 函式

Node.js Function 函式

函式方法

变数 说明
Function.call() 执行函式,并改变函式中的 this 物件为指定变数,函式参数依序带入
Function.apply() 执行函式,并改变函式中的 this 物件为指定变数,函式参数为阵列
Function.bind() 建立函式,并改变函式中的 this 物件为指定变数,下次呼叫时会使用改变过后的 this 物件执行

绑定 this 方式

  • callapply 皆是直接执行函式,只是参数传入方式不同
  • 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

call

传入参数第一个是要改变的 this 变数,后面是函式需要用的参数,依序列出

Function.call(要改变的this, 参数1, 参数2...)

apply

传入参数只有 2 个,函式用的参数用阵列包起来传入

Function.apply(要改变的this, [参数1, 参数2...])

bind

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 建立 Function 实例

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 箭头函式