how to call apply and bind in javascript - Lee-hyuna/33-js-concepts-kr GitHub Wiki
How-to: call() , apply() and bind() in JavaScript
μ΄ κΈμμ κ°λ¨ν μμ λ₯Ό ν΅ν΄ μλ°μ€ν¬λ¦½νΈμ call()
, apply()
κ·Έλ¦¬κ³ bind()
λ©μλμ μ°¨μ΄μ μ λ
Όν κ²μ΄λ€. ν¨μλ μλ°μ€ν¬λ¦½νΈμμ Objectμ΄κΈ° λλ¬Έμ, μ΄ 3κ°μ§ λ©μλλ ν¨μμ νΈμΆμ μ μ΄νλλ° μ¬μ©λλ€. ECMAScript3μλ call()
λ° apply()
κ° λμ
λμκ³ , ECMAScript5μμ bind()
κ° μΆκ°λμλ€.
μ¬μ©
call()
/apply()
λ₯Ό μ¬μ©νμ¬ ν¨μλ₯Ό μ¦μ νΈμΆν μ μλ€. bind()
λ λμ€μ μ€νλ λ μλμ ν¨μλ₯Ό νΈμΆνλ μ¬λ°λ₯Έ 컨ν
μ€νΈ("this")λ₯Ό κ°λ λ°μΈλ© ν¨μλ₯Ό λ°ννλ€. κ·Έλμ bind()
λ ν¨μκ° νΉμ μ΄λ²€νΈμμ λμ€μ νΈμΆλμ΄μΌ ν κ²½μ°μ μ μ©νκ² μ¬μ©ν μ μλ€.
μλ°μ€ν¬λ¦½νΈμ "this"λ₯Ό μ΄ν΄νλ €λ©΄ Understanding "This" in JavaScript κΈμ μ°Έμ‘°ν΄λΌ.
call()
or Function.prototype.call()
call()
μ λν κ°λ¨ν μμ λ₯Ό νμΈν΄ 보μ.
//Demo with javascript .call()
var obj = {name:"Niladri"};
var greeting = function(a,b,c){
return "welcome "+this.name+" to "+a+" "+b+" in "+c;
};
console.log(greeting.call(obj,"Newtown","KOLKATA","WB"));
// returns output as welcome Niladri to Newtown KOLKATA in WB
call()
λ©μλμ 첫λ²μ§Έ νλΌλ―Έν°λ ν¨μκ° νΈμΆλλ λμμΈ "this" κ°μ μ€μ νλ€. μμ κ²½μ°μλ "obj"μ΄λ€.
λλ¨Έμ§ λ§€κ°λ³μλ μ€μ ν¨μμ λν λν μΈμλ€μ΄λ€.
apply()
or Function.prototype.apply()
apply()
μ λν κ°λ¨ν μμ λ₯Ό νμΈν΄ 보μ.
//Demo with javascript .apply()
var obj = {name:"Niladri"};
var greeting = function(a,b,c){
return "welcome "+this.name+" to "+a+" "+b+" in "+c;
};
// array of arguments to the actual function
var args = ["Newtown","KOLKATA","WB"];
console.log("Output using .apply() below ")
console.log(greeting.apply(obj, args));
/* The output will be Output using .apply() below welcome Niladri to Newtown KOLKATA in WB */
d
call()
λ©μλμ λ§μ°¬κ°μ§λ‘ apply()
λ©μλμ 첫 λ²μ§Έ 맀κ°λ³μλ ν¨μκ° νΈμΆλλ λμμΈ "this" κ°μ μ€μ νλ€. μμ κ²½μ°μ "obj" κ°μ²΄μ΄λ€. apply()
μ call()
μ μ μΌν μ°¨μ΄λ λ λ²μ§Έ νλΌλ―Έν°μ΄λ€. apply()
λ λ°°μ΄λ‘ μ€μ ν¨μμ λν μΈμλ₯Ό λ°μ λ€μΈλ€.
bind()
or Function.prototype.bind()
bind()
μ λν κ°λ¨ν μμ λ₯Ό νμΈν΄ 보μ.
//Use .bind() javascript
var obj = {name:"Niladri"};
var greeting = function(a,b,c){
return "welcome "+this.name+" to "+a+" "+b+" in "+c;
};
//creates a bound function that has same body and parameters
var bound = greeting.bind(obj);
console.dir(bound); ///returns a function
console.log("Output using .bind() below ");
console.log(bound("Newtown","KOLKATA","WB"));
//call the bound function
/* the output will be Output using .bind() below welcome Niladri to Newtown KOLKATA in WB */
μμ μ½λ μνμμ bind()
λ λμ€μ νΈμΆ λ 컨ν
μ€νΈκ° μλ λ°μ΄λ ν¨μλ₯Ό λ°ννκ³ μλ€. λ€μκ³Ό κ°μ΄ μ½μμμ λ°μ΄λ ν¨μλ₯Ό λ³Ό μ μλ€.
bind() λ©μλμ 첫 λ²μ§Έ 맀κ°λ³μλ λ°μΈλ© ν¨μκ° νΈμΆλ λ λμ ν¨μμ "this" κ°μ μ€μ νλ€. λ°μΈλ© ν¨μκ° "new" μ°μ°μλ₯Ό μ¬μ©νμ¬ κ΅¬μ±λ κ²½μ° μ²« λ²μ§Έ νλΌλ―Έν°μ κ°μ 무μλλ€λ μ μ μ μνλΌ. λλ¨Έμ§ λ§€κ° λ³μλ λμ ν¨μλ₯Ό νΈμΆ ν λ λ°μΈλ λ ν¨μμ μ 곡λ μΈμ μμ μΆκ°λλ μΈμλ‘ μ λ¬λλ€.
μ¬κΈ°κΉμ§μ΄λ€. μ½μ΄μ£Όμ΄μ κ°μ¬ λ리며 μ΄ κ²μλ¬Όμ΄ μλ°μ€ν¬λ¦½νΈμ apply()
, call ()
λ° bind ()
λ©μλμ κ΄λ ¨λ λ¬Έμ λ₯Ό κ²ͺκ³ μλ μ΄λ³΄μμκ² λμμ΄λκΈ°λ₯Ό λ°λλ€.