call

假設我們有一個程式:

1
2
3
4
5
6
7
8
9
const person = {
firstName: 'Green',
lastName: 'tea',
fullname: function() {
return this.firstName + ' ' + this.lastName;
}
}

console.log(person.fullname());

將它輸出會是Green tea。
不過這樣的設計,如果你要宣告很多個person就會重複宣告fullname。
例如:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
const person1 = {
firstName: 'Green',
lastName: 'tea',
fullname: function() {
return this.firstName + ' ' + this.lastName;
}
}

const person2 = {
firstName: 'Oolong',
lastName: 'tea',
fullname: function() {
return this.firstName + ' ' + this.lastName;
}
}

所以我們可以使用call來達成

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
const person = {
fullname: function() {
return this.firstName + ' ' + this.lastName;
}
}

const person1 = {
firstName: 'Green',
lastName: 'tea',
}

const person2 = {
firstName: 'Oolong',
lastName: 'tea',
}

console.log(person.fullname.call(person1));
console.log(person.fullname.call(person2));

apply

現在有一個程式長這樣:

1
2
3
4
5
const obj = { name: 'John' };
let hello = function(a, b) {
return `${a} ${this.name} ${b}`;
}
console.log(greeting.call(obj, 'Hello', 'How are you'));

call的用法如之前提到的,把物件call特定的對象可以取用。
此外,call後面是可以接其他參數的,以這個例子,後面放了Hello 和 How are you
所以輸出會是:
Hello John How are you

換成apply的用法:

1
2
3
4
5
const obj = { name: 'John' };
let hello = function(a, b) {
return `${a} ${this.name} ${b}`;
}
console.log(greeting.apply(obj, ['Hello', 'How are you']));

apply的用法跟call很像,比較不同的地方是,後面接的參數是使用array。
假設今天你希望使用array用在max上,但是裡面吃的參數是seperated的:

1
2
const list = [2, 1, 5];
console.log(Math.max(2, 1, 5));

這個時候你可以使用apply:

1
2
const list = [2, 1, 5];
console.log(Math.max.apply(null, list));

以這個例子,不需要assign其他東西,所以第一個參數使用null。

bind

當我們要把指定的物件綁定到對應的對象,我們會使用bind。

1
2
3
4
5
6
7
8
const obj = { name: 'John' };
let hello = function(a, b) {
return `${a} ${this.name} ${b}`;
}

let johnSayHello = hello.bind(obj);

console.log(johnSayHello('Hello', 'How are you'));

Comment