Call, Apply, Bind
0.関数呼び出し、適用、バインド
2種類のJavaScriptメソッド
1.数値、配列、文字列...メソッド(math,map,split...)
2.関数メソッド(call、apply、bind)
関数呼び出しの2種類
1.関数名にかっこを付ける
2. call, apply, bind
1.呼び出しと適用
用法:fn.call(thisArg [,arg1[,arg2[,...]]])
fn.apply(thisArg, [argsArray])
1)call,applyの最初のパラメータはthis,2番目のパラメータはオブジェクトのパラメータである.以下の例1に示すように、applyの第2の因子は配列形式で受信される.
例1
const example = function(a, b, c) {
return a + b + c;
};
example(1, 2, 3);
example.call(null, 1, 2, 3);
examply.apply(null, [1, 2, 3]);
例1-2
const obj = {
string: 'zero',
yell: function() {
alert(this.string);
};
};
const obj2 = {
string: 'what?'
};
obj.yell(); // 'zero';
obj.yell.call(obj2); // 'what?'
2)関数にはargumentsという類似配列があり,これらのargumentsを操作する際に関数を使用する方法がある.例2
const example = function() {
console.log(Array.prototype.join.call(arguments));
};
example(1, 'string', true); // '1, string, true'
図に示すように、同様の配列であるが、callで置き換えることで、配列の方法を利用することができる.2. bind
用法:fn.bind(thisArg [,arg1[,arg2[,...]]])
bindはcall、applyのように関数が指す値を変更しますが、呼び出されません.したがって、変数に割り当てられて呼び出されます.
const student = person2.study.bind(person1) // 변수에 할당
student() // 호출
3. Examples
Call:
function cat (q, w, e) {
return console.log(this.dog ,q,w,e);
};
cat(1, 2, 3);
const that = {
dog: 'bark'
}
cat.call(that, 1, 2, 3);
// expected output: undefined 1 2 3
// expected output: bark 1 2 3
Apply:function cat (q, w, e) {
return console.log(this.dog ,q,w,e);
};
cat(1, 2, 3);
const that = {
dog: 'bark'
}
cat.apply(that, [1, 2, 3]);
// expected output: undefined 1 2 3
// expected output: bark 1 2 3
Bind:const module = {
x: 42,
getX: function() {
return this.x;
}
};
const unboundGetX = module.getX;
console.log(unboundGetX());
// expected output: undefined
const boundGetX = unboundGetX.bind(module);
console.log(boundGetX());
// expected output: 42
Reference
この問題について(Call, Apply, Bind), 我々は、より多くの情報をここで見つけました https://velog.io/@syg0713/Call-Apply-Bindテキストは自由に共有またはコピーできます。ただし、このドキュメントのURLは参考URLとして残しておいてください。
Collection and Share based on the CC Protocol