JavaScript의 call(), apply() 및 bind() 설명
이 기사에서는 다음 세 가지 함수 메서드에 대해 자세히 알아보겠습니다.
기본적으로 함수를 호출하는 데 사용됩니다(바인드 제외, bind()는 필요에 따라 사용할 수 있는 새 함수를 반환합니다). 그것들은 모두 컨텍스트에 따라
this 값을 취하여 해당 컨텍스트에서 기능을 실행합니다. 하나하나 자세히 살펴보겠습니다.전화()
MDN definition : call() 메서드는 개별적으로 제공된 주어진 this 값과 인수로 함수를 호출합니다.
Syntax: func.call([thisArg[, arg1, arg2, ...argN]])
-
thisArg: optional (this will be the value upon which the function would call)
-
arg1, arg2, ...argN: optional (arguments of the function)
- the first argument represents a value on which the function would call (it refers to the current object/the calling object)
- other arguments represent the value to the parameter of the function
예를 살펴보겠습니다.
// defining a global variable
var lastName = 'global_name';
const func = function(firstName) {
return firstName + " " + this.lastName; /** the value of 'this'
is defined how we call the function */
}
// this object is passed as the first argument to the call method
var person = {
lastName: 'person_name'
}
// calling the function usually
func('Sachin'); // Sachin global_name
/** calling the function using the call method and setting the
'this' value to the 'person' object */
func.call(person, 'Sachin'); // Sachin person_name
// using call method without passing the first argument
func.call(); // undefined global_name
// passing the first argument as null or undefined
func.call(null, 'Sachin'); // Sachin global_name
func.call(undefined, 'Sachin'); // Sachin global_name
/******************** in strict mode*****************/
func.call(); /** Cannot read property 'lastName' of undefined*/
func.call(null, 'Sachin'); /** Cannot read property 'lastName' of null*/
func.call(undefined, 'Sachin'); /** Cannot read property
'lastName' of undefined*/
예제에서 볼 수 있듯이 call 메서드를 사용하여 모든 개체에서 함수를 호출할 수 있습니다.
When usually calling the function then this value will set to the global object window. This window object is having a property lastName which we defined globally in our code will return from the function.
When calling the function using the call method and passing the first argument a person object then this value will set to that person object (not window object this time) and its lastName property will return.
Using the call method without passing any arguments, this value will set to the global object window and its property lastName will return.
When the first argument passed is null or undefined then still the this will set to the global window object in this case.
주의: 엄격 모드의 경우
In 'strict mode', the value of this will be undefined. To know about strict mode refer to this documentation.
적용하다()
Syntax: func.apply(thisArg, [ argsArray])
-
thisArg: (this will be the value upon which the function would call)
-
argsArray: optional (arguments of the function passed in an array)
apply()는 배열을 두 번째 인수로 사용하고 해당 배열의 구성원을 호출 함수에 인수로 전달한다는 점을 제외하면 call()과 거의 유사합니다.
예시:
var name = 'Sachin';
const func = function (age, hobby) {
return (this.name + ' is ' + age + ' years old and his hobby is '
+ hobby);
};
var person = {
name: 'John'
}
func(); /** Sachin is undefined years old and his
hobby is undefined*/
func.apply(); /** Sachin is undefined years old and his
hobby is undefined*/
console.log(func() === func.apply()); /** true*/
func('15', 'writing'); /** Sachin is 15 years old and his
hobby is writing*/
func.apply(undefined, ['15', 'writing']); /** Sachin is 15 years
old and his hobby is writing*/
func.apply(null, ['15', 'writing']); /** Sachin is 15 years
old and his hobby is writing*/
/********* changing 'this' to 'person' object*********/
func.apply(person, ['20', 'music']); /** John is 20 years
old and his hobby is music*/
/**************** strict mode ***************/
/** Cannot read property 'name' of undefined*/
func();
func('15', 'writing');
func.apply();
func.apply(undefined, ['15', 'writing']);
/** Cannot read property 'name' of null */
func.apply(null, ['15', 'writing']);
묶다()
Syntax: func.bind(thisArg[, arg1[, arg2[, ...argN]]])
bind() 메서드는 func 함수의 복사본을 만들고 반환합니다. 해당 새 함수가 호출되면 this 값이 thisArg 에서 제공하는 값으로 설정됩니다. arg1, arg2,..., argN은 새로 반환된 함수의 인수 앞에 추가되는 인수입니다.
예를 들어 이것을 이해합시다.
// defining a person object
/** this object has a property 'age' and a method
'getNameAndAge' */
const person = {
age: 42,
getNameAndAge: function(name) {
return name + ' ' + this.age;
}
}
// calling the method on the 'person' object directly
person.getNameAndAge('Sachin'); // Sachin 42
// assigning the reference of the method to variable nameAndAge
const nameAndAge = person.getNameAndAge;
// calling the function assigned to nameAndAge by referencing it
nameAndAge('Sachin'); /** Sachin undefined (the function gets
invoked at the global scope)*/
// use of bind method
const boundNameAndAge = nameAndAge.bind(person, 'Sachin');
boundNameAndAge() /** Sachin 42 (bind method creates
a new function and bounds 'this' value to 'person' object)*/
// bind without any arguments
const boundNameAndAge = nameAndAge.bind();
boundNameAndAge('Sachin') // Sachin undefined
// setting 'this' to 'undefined'
const boundNameAndAge = nameAndAge.bind(undefined, 'Sachin');
boundNameAndAge() // Sachin undefined
// setting 'this' to 'null'
const boundNameAndAge = nameAndAge.bind(null, 'Sachin');
boundNameAndAge() // Sachin undefined
nameAndAge('Sachin');를 실행할 때 전역 범위에서 해당 함수를 실행하고 있으며 여기에서 this는 전역window 개체를 참조하며 전역 범위에서 age를 정의하지 않았기 때문에 반환됩니다. undefined . const boundNameAndAge = nameAndAge.bind(person, 'Sachin');bind 메서드는 nameAndAge 함수의 복사본을 만들어 반환하고 this를 person 개체로 설정합니다. 새로 생성된 함수를 변수boundNameAndAge에 할당합니다. boundNameAndAge()를 실행하면 this가 person로 설정되고 age 객체의 person 속성이 반환됩니다.
인수가 없거나 this가 null 또는 undefined로 설정된 경우 새로 생성된 함수의 this 값은 실행 범위의 this에 의해 결정됩니다.
결론
call() 및 apply()는 함수를 즉시 실행하는 반면 bind()는 새 함수를 반환합니다. 함수가 실행되는 객체/값은 컨텍스트에 의해 정의된 this 값에 따라 다릅니다.
Thanks for reading. If you found this article helpful please like and share it with others so that they will also get the benefit. Feedbacks are welcome: | |
Reference
이 문제에 관하여(JavaScript의 call(), apply() 및 bind() 설명), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다
https://dev.to/sachinkoli/call-apply-and-bind-in-javascript-explained-4kk2
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
우수한 개발자 콘텐츠 발견에 전념
(Collection and Share based on the CC Protocol.)
Syntax: func.call([thisArg[, arg1, arg2, ...argN]])
- thisArg: optional (this will be the value upon which the function would call)
- arg1, arg2, ...argN: optional (arguments of the function)
- the first argument represents a value on which the function would call (it refers to the current object/the calling object)
- other arguments represent the value to the parameter of the function
예를 살펴보겠습니다.
// defining a global variable
var lastName = 'global_name';
const func = function(firstName) {
return firstName + " " + this.lastName; /** the value of 'this'
is defined how we call the function */
}
// this object is passed as the first argument to the call method
var person = {
lastName: 'person_name'
}
// calling the function usually
func('Sachin'); // Sachin global_name
/** calling the function using the call method and setting the
'this' value to the 'person' object */
func.call(person, 'Sachin'); // Sachin person_name
// using call method without passing the first argument
func.call(); // undefined global_name
// passing the first argument as null or undefined
func.call(null, 'Sachin'); // Sachin global_name
func.call(undefined, 'Sachin'); // Sachin global_name
/******************** in strict mode*****************/
func.call(); /** Cannot read property 'lastName' of undefined*/
func.call(null, 'Sachin'); /** Cannot read property 'lastName' of null*/
func.call(undefined, 'Sachin'); /** Cannot read property
'lastName' of undefined*/
예제에서 볼 수 있듯이 call 메서드를 사용하여 모든 개체에서 함수를 호출할 수 있습니다.
When usually calling the function then
thisvalue will set to the global objectwindow. Thiswindowobject is having a propertylastNamewhich we defined globally in our code will return from the function.When calling the function using the call method and passing the first argument a
personobject thenthisvalue will set to thatpersonobject (notwindowobject this time) and itslastNameproperty will return.Using the call method without passing any arguments,
thisvalue will set to the global objectwindowand its propertylastNamewill return.When the first argument passed is
nullorundefinedthen still thethiswill set to the globalwindowobject in this case.주의: 엄격 모드의 경우
In 'strict mode', the value of
thiswill beundefined. To know about strict mode refer to this documentation.
적용하다()
Syntax: func.apply(thisArg, [ argsArray])
- thisArg: (this will be the value upon which the function would call)
- argsArray: optional (arguments of the function passed in an array)
apply()는 배열을 두 번째 인수로 사용하고 해당 배열의 구성원을 호출 함수에 인수로 전달한다는 점을 제외하면 call()과 거의 유사합니다.
예시:
var name = 'Sachin'; const func = function (age, hobby) { return (this.name + ' is ' + age + ' years old and his hobby is ' + hobby); }; var person = { name: 'John' } func(); /** Sachin is undefined years old and his hobby is undefined*/ func.apply(); /** Sachin is undefined years old and his hobby is undefined*/ console.log(func() === func.apply()); /** true*/ func('15', 'writing'); /** Sachin is 15 years old and his hobby is writing*/ func.apply(undefined, ['15', 'writing']); /** Sachin is 15 years old and his hobby is writing*/ func.apply(null, ['15', 'writing']); /** Sachin is 15 years old and his hobby is writing*/ /********* changing 'this' to 'person' object*********/ func.apply(person, ['20', 'music']); /** John is 20 years old and his hobby is music*/ /**************** strict mode ***************/ /** Cannot read property 'name' of undefined*/ func(); func('15', 'writing'); func.apply(); func.apply(undefined, ['15', 'writing']); /** Cannot read property 'name' of null */ func.apply(null, ['15', 'writing']);
묶다()
Syntax: func.bind(thisArg[, arg1[, arg2[, ...argN]]])
bind() 메서드는 func함수의 복사본을 만들고 반환합니다.해당 새 함수가 호출되면 this값이thisArg에서 제공하는 값으로 설정됩니다.arg1, arg2,..., argN은 새로 반환된 함수의 인수 앞에 추가되는 인수입니다.
예를 들어 이것을 이해합시다.
// defining a person object /** this object has a property 'age' and a method 'getNameAndAge' */ const person = { age: 42, getNameAndAge: function(name) { return name + ' ' + this.age; } } // calling the method on the 'person' object directly person.getNameAndAge('Sachin'); // Sachin 42 // assigning the reference of the method to variable nameAndAge const nameAndAge = person.getNameAndAge; // calling the function assigned to nameAndAge by referencing it nameAndAge('Sachin'); /** Sachin undefined (the function gets invoked at the global scope)*/ // use of bind method const boundNameAndAge = nameAndAge.bind(person, 'Sachin'); boundNameAndAge() /** Sachin 42 (bind method creates a new function and bounds 'this' value to 'person' object)*/ // bind without any arguments const boundNameAndAge = nameAndAge.bind(); boundNameAndAge('Sachin') // Sachin undefined // setting 'this' to 'undefined' const boundNameAndAge = nameAndAge.bind(undefined, 'Sachin'); boundNameAndAge() // Sachin undefined // setting 'this' to 'null' const boundNameAndAge = nameAndAge.bind(null, 'Sachin'); boundNameAndAge() // Sachin undefinednameAndAge('Sachin');를 실행할 때 전역 범위에서 해당 함수를 실행하고 있으며 여기에서this는 전역window개체를 참조하며 전역 범위에서age를 정의하지 않았기 때문에 반환됩니다.undefined.const boundNameAndAge = nameAndAge.bind(person, 'Sachin');bind메서드는 nameAndAge 함수의 복사본을 만들어 반환하고this를person개체로 설정합니다. 새로 생성된 함수를 변수boundNameAndAge에 할당합니다.boundNameAndAge()를 실행하면this가person로 설정되고age객체의person속성이 반환됩니다.
인수가 없거나 this가null또는undefined로 설정된 경우 새로 생성된 함수의this값은 실행 범위의this에 의해 결정됩니다.
결론
call() 및 apply()는 함수를 즉시 실행하는 반면 bind()는 새 함수를 반환합니다. 함수가 실행되는 객체/값은 컨텍스트에 의해 정의된 this값에 따라 다릅니다.
Thanks for reading. If you found this article helpful please like and share it with others so that they will also get the benefit. Feedbacks are welcome: | |
Reference
이 문제에 관하여(JavaScript의 call(), apply() 및 bind() 설명), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다 https://dev.to/sachinkoli/call-apply-and-bind-in-javascript-explained-4kk2텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
우수한 개발자 콘텐츠 발견에 전념
(Collection and Share based on the CC Protocol.)