JS .call () 메서드를 사용하는 이유는 무엇입니까?
JS에서 call () 메서드를 사용하는 이유가 무엇인지 관심이 있습니다. 일반적인 호출 방법과 중복되는 것 같습니다 this.
예를 들어, call () 코드가 있습니다.
var obj = {
objType: "Dog"
}
f = function(did_what, what) {
alert(this.objType + " " + did_what + " " + what);
}
f.call(obj, "ate", "food");
출력은 "Dog ate food"입니다. 그러나 동일한 결과로 객체에 기능을 할당 할 수 있습니다.
var obj = {
objType: "Dog"
}
f = function(did_what, what) {
alert(this.objType + " " + did_what + " " + what);
}
obj.a = f;
obj.a("ate", "food");
결과는 동일합니다. 그러나이 방법은 더 이해하기 쉽고 사용하기 편리합니다. 왜 call ()이 필요한가요?
call호출 된 함수에서 사용할 범위를 제어하려는 경우 사용됩니다. this키워드가 함수를 할당 한 범위가 아닌 다른 것이 되기를 원할 수 있습니다.이 경우 자체 범위로 함수를 사용 call하거나 apply호출 할 수 있습니다 .
F.ex, "private"함수를 사용할 때와 같이 범위 밖에서 유틸리티 메서드를 호출 할 수도 있습니다.
var obj = (function() {
var privateFn = function() {
alert(this.id);
}
return {
id: 123,
publicFn: function() {
privateFn.call(this);
}
};
}());
obj.publicFn();
위의 예에서는 privateFn노출되지 obj않지만 공용 범위의 일부인 것처럼 구성 할 수 있습니다 ( this동일한 방식으로 사용).
2017 업데이트
Function.prototype을 통한 모든 함수에는 .call메서드가 있습니다. 사용하는 이유 .call()는 " this" 변수가 참조하는 것을 지정 하기위한 것입니다.
MDN은 다음을 지정합니다.
이
call()메서드는 주어진이 값과 개별적으로 제공된 인수를 사용하여 함수를 호출합니다.
다음을 고려하세요:
function x() {
return this;
}
x()
엄격 모드에서는 엄격 하지 않은 모드로 x()반환 undefined되며 Window브라우저 컨텍스트에서 전역 개체를 반환합니다 .
예를 들어 .call()" this" 이 무엇을 의미 하는지 알려줍니다 .
function x() {
return this;
}
var obj = {
myName : 'Robert',
myLocation : 'Earth'
}
x.call(obj);
Result: {myName: "Robert", myLocation: "Earth"}. In the above example we are specifying the obj object as the value of this inside the function x()
It can be used to emulate inheritance in OOP.
Example:
var Robert = {
name: "Robert Rocha",
age: 12,
height: "5,1",
sex: "male",
describe: function() {
return "This is me " + this.name + " " + this.age + " " + this.height + " " + this.sex;
}
};
Lets say that the above is a master object(prototype) and you want to inherit the function describe in another object:
var Richard = {
name: "Richard Sash",
age: 25,
height: "6,4",
sex: "male",
}
The Richard object does not have the describe function and you want to simply inherit ,so to speak, the function. You would do it like so:
console.log( Robert.describe.call( Richard ) );
Output: This is me Richard Sash 25 6,4 male
You would probably use the second way in your example, but sometimes you want to use one object's functions on another object. An example would be using Array methods on Array-like objects like NodeLists
var el = document.getElementById("foo");
[].forEach.call(el.children, function(child, index) {
//Iterate over an element's children, performing an action on each one
});
It's to do with the concept of a first class function. Basically languages like Javascript allow you to treat functions as things their own right. Functions can be stored in variables or passed to other functions.
call() provides a way to execute a free standing function not attached to any other object.
참고URL : https://stackoverflow.com/questions/9001830/the-reason-to-use-js-call-method
'IT Share you' 카테고리의 다른 글
| Custom ViewGroup 내에서 XML-Layout-File을 올바르게 팽창시키는 방법은 무엇입니까? (0) | 2020.12.11 |
|---|---|
| 조건이있는 SQL 합계 (0) | 2020.12.11 |
| 명령 줄에서 입력 숨기기 (0) | 2020.12.11 |
| WinRT에서 리플렉션을 사용하여 호출 된 비동기 개인 메서드를 기다리는 방법은 무엇입니까? (0) | 2020.12.11 |
| iOS : URL에서 "새로 실행"앱을 디버그하는 방법 (0) | 2020.12.11 |