콜과 신청의 차이점은 무엇입니까?
를 사용하는 것의 차이점은 무엇입니까?Function.prototype.apply()
★★★★★★★★★★★★★★★★★」Function.prototype.call()
능을호 호출 ??? ???
var func = function() {
alert('hello!');
};
func.apply();
»func.call();
앞서 말한 두 가지 방법 사이에 성능 차이가 있습니까??call
에 걸쳐서apply
리고고 그???
점은 '하다'는 것입니다.apply
하면 함수를 할 수 .arguments
call
에서는 파라미터를 명시적으로 나열해야 합니다.유용한 니모닉은 "A는 배열, C는 쉼표"입니다.
유사 구문:
theFunction.apply(valueForThis, arrayOfArgs)
theFunction.call(valueForThis, arg1, arg2, ...)
또한 ES6에서는 어레이를 사용하여call
여기서 호환성을 확인할 수 있습니다.
샘플 코드:
function theFunction(name, profession) {
console.log("My name is " + name + " and I am a " + profession +".");
}
theFunction("John", "fireman");
theFunction.apply(undefined, ["Susan", "school teacher"]);
theFunction.call(undefined, "Claude", "mathematician");
theFunction.call(undefined, ...["Matthew", "physicist"]); // used with the spread operator
K. 스캇 알렌은 그 문제에 관해 훌륭한 글을 쓰고 있다.
기본적으로 함수 인수를 처리하는 방법은 다릅니다.
apply() 메서드는 call()과 동일하지만 apply()는 두 번째 파라미터로 배열을 필요로 합니다.배열은 대상 메서드의 인수를 나타냅니다."
그래서:
// assuming you have f
function f(message) { ... }
f.call(receiver, "test");
f.apply(receiver, ["test"]);
는, 「할 수 있는 타이밍」을 사용해 주세요.apply
또는 인수 와 같은 오브젝트 내에 예: "인수")arguments
arguments.object 。call
그렇지 않으면 인수를 배열로 래핑할 필요가 없기 때문입니다.
f.call(thisObject, a, b, c); // Fixed number of arguments
f.apply(thisObject, arguments); // Forward this function's arguments
var args = [];
while (...) {
args.push(some_value());
}
f.apply(thisObject, args); // Unknown number of arguments
) 어떤 는 (예시와 같이)가 .call
내가 경찰서에 전화할 테니까 apply
는 함수를 (존재하지 않는) 인수에 적용하고 있음을 나타냅니다.
없을 다만, 에는요.다,,apply
묶습니다(g인배(((((((((((((((((((((:f.apply(thisObject, [a, b, c])
f.call(thisObject, a, b, c)
테스트하지 않았기 때문에 차이가 있을 수 있지만 브라우저에 따라 다릅니다. 그럴 것이다call
및 인수가 더 .apply
더 빠를 거예요.
여기 좋은 니모닉이 있습니다.Apply는 Arrays를 사용하며 항상 하나 또는 두 개의 인수를 사용합니다.[콜(Call)]를 사용할 때는 인수 수를 카운트해야 합니다.
오래된 토픽이지만 .call이 .apply보다 약간 빠르다는 것을 지적하고 싶습니다.이유는 정확히 말씀드릴 수 없습니다.
jsPerf, http://jsperf.com/test-call-vs-apply/3 를 참조해 주세요.
UPDATE!
더글러스 크록포드는 두 가지 차이점에 대해 간단히 언급했는데, 이는 성능 차이를 설명하는 데 도움이 될 수 있습니다.http://youtu.be/ya4UHuXNygM?t=15m52s
Apply는 일련의 인수를 사용하는 반면 Call은 0개 이상의 개별 파라미터를 사용합니다.아하하!
.apply(this, [...])
.call(this, param1, param2, param3, param4...)
Closure(폐쇄)에서 발췌한 내용을 따릅니다. 마이클 볼린의 '결정적 가이드'조금 길어 보일 수도 있지만, 통찰력이 풍부합니다.부록 B에서.자주 오해되는 JavaScript 개념":
what?this
되었을 때
의 할 때foo.bar.baz()
「」foo.bar
을 사용하다때, 됩니다.this
:
var obj = {};
obj.value = 10;
/** @param {...number} additionalValues */
obj.addValues = function(additionalValues) {
for (var i = 0; i < arguments.length; i++) {
this.value += arguments[i];
}
return this.value;
};
// Evaluates to 30 because obj is used as the value for 'this' when
// obj.addValues() is called, so obj.value becomes 10 + 20.
obj.addValues(20);
함수가 호출되었을 때 명시적인 수신기가 없는 경우 글로벌오브젝트가 수신기가 됩니다.47 페이지의 "goog.global"에서 설명한 바와 같이 웹 브라우저에서 JavaScript가 실행될 때 창은 글로벌 객체입니다.이로 인해 다음과 같은 놀라운 동작이 발생합니다.
var f = obj.addValues;
// Evaluates to NaN because window is used as the value for 'this' when
// f() is called. Because and window.value is undefined, adding a number to
// it results in NaN.
f(20);
// This also has the unintentional side effect of adding a value to window:
alert(window.value); // Alerts NaN
그럼에도 불구하고.obj.addValues
★★★★★★★★★★★★★★★★★」f
함수를 참조하고 때문에, 호출시에 동작이 .이러한 함수는, 콜 마다 수신측의 값이 다르기 때문에, 호출시에 다른 동작을 합니다. 때문에, 이 는, 이 때,this
, 을합니다.this
는 호출되었을 때 올바른 값을 가집니다.하자면, ★★★★★★★★★★★★★★★★★★★★★」this
은 「」이 됩니다.그러면f(20)
★★★★★★★★★★★★★★★★★」obj.addValues(20)
똑같을 거예요.
함수는 JavaScript에서 1등급 객체이기 때문에 고유한 메서드를 가질 수 있습니다.에는 다 .call()
★★★★★★★★★★★★★★★★★」apply()
에 의해, 리시버를 재정의할 수 , 「리시버」는 「, 「리시버」의 「리시버」의 「리시버」의 「리시버」의 「리시버」의 「리시버」의 「리시버」의 「리시버」의 「리시버」를 할 수 있습니다.this
는 함수를 호출할 때 참조합니다.메서드 시그니처는 다음과 같습니다.
/**
* @param {*=} receiver to substitute for 'this'
* @param {...} parameters to use as arguments to the function
*/
Function.prototype.call;
/**
* @param {*=} receiver to substitute for 'this'
* @param {Array} parameters to use as arguments to the function
*/
Function.prototype.apply;
「 」의 한 는, 「 」입니다.call()
★★★★★★★★★★★★★★★★★」apply()
라는 것이다.call()
는 함수 인수로 하는 반면, 는 함수 파라미터를 수신합니다.apply()
합니다.
// When f is called with obj as its receiver, it behaves the same as calling
// obj.addValues(). Both of the following increase obj.value by 60:
f.call(obj, 10, 20, 30);
f.apply(obj, [10, 20, 30]);
f
★★★★★★★★★★★★★★★★★」obj.addValues
동일한 기능을 참조한다.
obj.addValues.call(obj, 10, 20, 30);
obj.addValues.apply(obj, [10, 20, 30]);
어느 쪽도 그렇지 않기 call()
않다apply()
는, 리시버 인수가 되어 있지 않은 , 을 사용해 .하다
// Both statements evaluate to NaN
obj.addValues.call(undefined, 10, 20, 30);
obj.addValues.apply(undefined, [10, 20, 30]);
「」의 값this
있을 수 없다null
★★★★★★★★★★★★★★★★★」undefined
함수가 호출되었을 때.null
★★★★★★★★★★★★★★★★★」undefined
로서 call()
★★★★★★★★★★★★★★★★★」apply()
대신 글로벌오브젝트가 리시버 값으로 사용됩니다.에서도 '이러다'라는 이름의 않은 .value
이치노
함수가 할당되어 있는 변수에 대한 지식이 없다고 생각하면 도움이 될 수 있습니다.이를 통해 함수가 정의될 때가 아니라 함수가 호출될 때 값이 바인딩된다는 생각을 강화할 수 있습니다.
추출 종료.
어떤 오브젝트가 다른 오브젝트의 기능을 빌리는 것이 도움이 되는 경우가 있습니다.즉, 빌리는 오브젝트는 단순히 빌려준 기능을 자신의 것과 같이 실행하는 것입니다.
작은 코드의 예:
var friend = {
car: false,
lendCar: function ( canLend ){
this.car = canLend;
}
};
var me = {
car: false,
gotCar: function(){
return this.car === true;
}
};
console.log(me.gotCar()); // false
friend.lendCar.call(me, true);
console.log(me.gotCar()); // true
friend.lendCar.apply(me, [false]);
console.log(me.gotCar()); // false
이러한 방법은 객체에 일시적인 기능을 제공하는 데 매우 유용합니다.
Call, Apply 및 Bind를 사용하는 다른 예.Call과 Apply의 차이는 분명하지만 Bind는 다음과 같이 동작합니다.
- Bind는 실행할 수 있는 함수의 인스턴스를 반환합니다.
- 첫 번째 매개 변수는 '이것'입니다.
- 두 번째 파라미터는 콤마로 구분된 인수 목록(Call 등)입니다.
}
function Person(name) {
this.name = name;
}
Person.prototype.getName = function(a,b) {
return this.name + " " + a + " " + b;
}
var reader = new Person('John Smith');
reader.getName = function() {
// Apply and Call executes the function and returns value
// Also notice the different ways of extracting 'getName' prototype
var baseName = Object.getPrototypeOf(this).getName.apply(this,["is a", "boy"]);
console.log("Apply: " + baseName);
var baseName = Object.getPrototypeOf(reader).getName.call(this, "is a", "boy");
console.log("Call: " + baseName);
// Bind returns function which can be invoked
var baseName = Person.prototype.getName.bind(this, "is a", "boy");
console.log("Bind: " + baseName());
}
reader.getName();
/* Output
Apply: John Smith is a boy
Call: John Smith is a boy
Bind: John Smith is a boy
*/
예를 들어 'valueFor'가다음 인수가 사용됩니다.
Array.prototype.push = function(element) {
/*
Native code*, that uses 'this'
this.put(element);
*/
}
var array = [];
array.push(1);
array.push.apply(array,[2,3]);
Array.prototype.push.apply(array,[4,5]);
array.push.call(array,6,7);
Array.prototype.push.call(array,8,9);
//[1, 2, 3, 4, 5, 6, 7, 8, 9]
** 파일: http://es5.github.io/ #x15.4.7*
Call()은 콤마로 구분된 인수를 사용합니다.다음은 예를 제시하겠습니다.
.call(scope, arg1, arg2, arg3)
apply()는 다음과 같은 일련의 인수를 사용합니다.
.apply(scope, [arg1, arg2, arg3])
다음은 몇 가지 사용 예를 제시하겠습니다.http://blog.i-evaluation.com/2012/08/15/javascript-call-and-apply/
Function.protype.apply()의 MDN 문서에서 다음을 수행합니다.
apply된 apply()를 합니다.
this
값 및 인수를 배열(또는 배열과 유사한 개체)로 제공합니다.구문
fun.apply(thisArg, [argsArray])
Function.protype.call()의 MDN 문서에서 다음을 수행합니다.
call된 call()을 사용하여 합니다.
this
값 및 인수를 개별적으로 제공합니다.구문
fun.call(thisArg[, arg1[, arg2[, ...]]])
JavaScript의 Function.apply 및 Function.call에서 다음을 수행합니다.
apply() 메서드는 call()과 동일하지만 apply()는 두 번째 파라미터로 배열을 필요로 합니다.배열은 대상 메서드의 인수를 나타냅니다.
코드 예:
var doSomething = function() {
var arr = [];
for(i in arguments) {
if(typeof this[arguments[i]] !== 'undefined') {
arr.push(this[arguments[i]]);
}
}
return arr;
}
var output = function(position, obj) {
document.body.innerHTML += '<h3>output ' + position + '</h3>' + JSON.stringify(obj) + '\n<br>\n<br><hr>';
}
output(1, doSomething(
'one',
'two',
'two',
'one'
));
output(2, doSomething.apply({one : 'Steven', two : 'Jane'}, [
'one',
'two',
'two',
'one'
]));
output(3, doSomething.call({one : 'Steven', two : 'Jane'},
'one',
'two',
'two',
'one'
));
여기 작은 게시물이 있습니다. 저는 여기에 이렇게 썼습니다.
http://sizeableidea.com/call-versus-apply-javascript/
var obj1 = { which : "obj1" },
obj2 = { which : "obj2" };
function execute(arg1, arg2){
console.log(this.which, arg1, arg2);
}
//using call
execute.call(obj1, "dan", "stanhope");
//output: obj1 dan stanhope
//using apply
execute.apply(obj2, ["dan", "stanhope"]);
//output: obj2 dan stanhope
//using old school
execute("dan", "stanhope");
//output: undefined "dan" "stanhope"
근본적인 차이는 입니다.call()
는 인수 목록을 받아들이지만,apply()
는 단일 인수 배열을 받아들입니다.
점은 '하다'는 것입니다.call()
따로따로 하고 함수 를 사용합니다.apply()
는 배열 내의 함수 인수를 사용합니다.
요약:.
다.call()
★★★★★★★★★★★★★★★★★」apply()
메서드입니다.Function.prototype
따라서 프로토타입 체인을 통해 모든 기능 객체에서 사용할 수 있습니다. 다.call()
★★★★★★★★★★★★★★★★★」apply()
인 '수치'로할 수 .this
.
「 」의 주된 call()
★★★★★★★★★★★★★★★★★」apply()
양쪽 call()
★★★★★★★★★★★★★★★★★」apply()
를 첫 합니다.this
기타 인수는 다음과 같이 다릅니다.
- ★★★★★★★★★★★★★★★★
call()
. - ★★★★★★★★★★★★★★★★
apply()
일련의 인수를 통과해야 합니다.
예:
let obj = {
val1: 5,
val2: 10
}
const summation = function (val3, val4) {
return this.val1 + this.val2 + val3 + val4;
}
console.log(summation.apply(obj, [2 ,3]));
// first we assign we value of this in the first arg
// with apply we have to pass in an array
console.log(summation.call(obj, 2, 3));
// with call we can pass in each arg individually
이러한 기능을 사용해야 하는 이유는 무엇입니까?
this
script는 값이 수 .「」의 값this
함수가 정의되었을 때가 아니라 함수가 실행되었을 때를 결정합니다.우리의 기능이 권리에 의존하는 경우this
할 수 .call()
★★★★★★★★★★★★★★★★★」apply()
을 사용하다예를 들어 다음과 같습니다.
var name = 'unwantedGlobalName';
const obj = {
name: 'Willem',
sayName () { console.log(this.name);}
}
let copiedMethod = obj.sayName;
// we store the function in the copiedmethod variable
copiedMethod();
// this is now window, unwantedGlobalName gets logged
copiedMethod.call(obj);
// we enforce this to be obj, Willem gets logged
아래와 같이 콜을 구별하여 메서드를 적용할 수 있습니다.
CALL : 인수가 있는 함수는 개별적으로 제공됩니다.전달할 인수를 알고 있거나 전달할 인수가 없는 경우 콜을 사용할 수 있습니다.
APPLY : 인수를 배열로 지정하여 함수를 호출합니다.몇 개의 인수가 함수에 전달될지 모르는 경우 apply를 사용할 수 있습니다.
apply over call을 사용하는 이점은 있습니다.인수의 수를 변경할 필요는 없습니다.전달된 어레이만 변경할 수 있습니다.
성능에는 큰 차이가 없습니다.다만, 어레이는 적용 방법으로 평가할 필요가 있기 때문에, 적용하는 것에 비해 호출이 고속이라고 말할 수 있습니다.
주된 차이점은 콜을 사용하면 정상적으로 범위를 변경하고 인수를 전달할 수 있지만 apply를 사용하면 인수를 배열로 사용하여 호출할 수 있다는 것입니다(어레이로 전달).하지만 코드로 무엇을 해야 하는가에 대해서는 거의 비슷합니다.
이 함수의 구문은 apply()의 구문과 거의 동일하지만 근본적인 차이점은 call()이 인수 목록을 받아들이는 반면 apply()는 단일 인수 배열을 받아들이는 것입니다.
보시다시피 큰 차이는 없지만 call() 또는 apply()를 사용하는 것이 좋습니다.예를 들어, 적용 방법을 사용하여 MDN에서 배열의 최소값과 최대값을 찾는 다음 코드를 참조하십시오.
// min/max number in an array
var numbers = [5, 6, 2, 3, 7];
// using Math.min/Math.max apply
var max = Math.max.apply(null, numbers);
// This about equal to Math.max(numbers[0], ...)
// or Math.max(5, 6, ...)
var min = Math.min.apply(null, numbers)
따라서 가장 큰 차이점은 우리가 주장을 전달하는 방식입니다.
★★★★★★★★★★★★★
function.call(thisArg, arg1, arg2, ...);
적용:
function.apply(thisArg, [argsArray]);
메서드와의 차이는 매개 변수를 전달하는 방법입니다.
"A는 배열, C는 쉼표"는 편리한 니모닉입니다.
는 둘 다 Call and Apply를 하기 위해 됩니다.this
값을 지정합니다.유일한 차이점은 이다.call
이 걸리다n+1
은 '1'입니다.this
★★★★★★★★★★★★★★★★★」'n' arguments
apply
주장만 합니다. 는 2번입니다.하나는this
하다
에서 알 수 apply
에 걸쳐서call
함수에 할 수 것, 즉 함수 을 다른 함수에 쉽게 위임할 수 있다는 것입니다.
function sayHello() {
console.log(this, arguments);
}
function hello() {
sayHello.apply(this, arguments);
}
var obj = {name: 'my name'}
hello.call(obj, 'some', 'arguments');
가 쉽게 위임했는지 .hello
로로 합니다.sayHello
를 사용합니다.apply
,에서는call
이것은 성취하기 매우 어렵다.
그럼에도 불구하고.call
★★★★★★★★★★★★★★★★★」apply
할 수 있지만, 한 할 수 곳이 합니다.call
, 사용할 수 것은 「」입니다.apply
상속을 지원하고 컨스트럭터를 호출하는 경우입니다.
다른 클래스를 확장하여 클래스를 만들 수 있는 기능을 제공합니다.
function makeClass( properties ) {
var ctor = properties['constructor'] || function(){}
var Super = properties['extends'];
var Class = function () {
// Here 'call' cannot work, only 'apply' can!!!
if(Super)
Super.apply(this,arguments);
ctor.apply(this,arguments);
}
if(Super){
Class.prototype = Object.create( Super.prototype );
Class.prototype.constructor = Class;
}
Object.keys(properties).forEach( function(prop) {
if(prop!=='constructor' && prop!=='extends')
Class.prototype[prop] = properties[prop];
});
return Class;
}
//Usage
var Car = makeClass({
constructor: function(name){
this.name=name;
},
yourName: function() {
return this.name;
}
});
//We have a Car class now
var carInstance=new Car('Fiat');
carInstance.youName();// ReturnsFiat
var SuperCar = makeClass({
constructor: function(ignore,power){
this.power=power;
},
extends:Car,
yourPower: function() {
return this.power;
}
});
//We have a SuperCar class now, which is subclass of Car
var superCar=new SuperCar('BMW xy',2.6);
superCar.yourName();//Returns BMW xy
superCar.yourPower();// Returns 2.6
여기에 조금 더 자세히 설명하겠습니다.
다음 2개의 콜은 거의 동등합니다.
func.call(context, ...args); // pass an array as list with spread operator
func.apply(context, args); // is same as using apply
약간의 차이밖에 없습니다.
spread
연산자...는 반복 가능한 전달을 허용합니다.args
이치노apply
는 배열과 같은 arg만을 받아들입니다.
따라서 이들 콜은 서로 보완합니다.우리가 반복할 수 있는 것을 기대하는 곳,call
어레이와 같은 기능을 기대할 수 있습니다.apply
실제 어레이와 같이 반복 가능하고 어레이와 유사한 객체의 경우 기술적으로 모든 객체를 사용할 수 있지만 대부분의 JavaScript 엔진이 내부적으로 최적화하기 때문에 적용이 더 빠를 수 있습니다.
call()
된 함수를 합니다.this
값 및 두 번째 매개 변수는 쉼표로 구분된 인수입니다.
object.someMethod.call( someObject, arguments )
apply()
method는 두 번째 인수가 인수 배열이라는 점을 제외하고 콜과 동일합니다.
object.someMethod.apply( someObject, arrayOfarguments )
var car = {
name: "Reno",
country: "France",
showBuyer: function(firstName, lastName) {
console.log(`${firstName} ${lastName} just bought a ${this.name} from ${this.country}`);
}
}
const firstName = "Bryan";
const lastName = "Smith";
car.showBuyer(firstName, lastName); // Bryan just bought a Reno from France
const obj = { name: "Maserati", country: "Italy" };
car.showBuyer.call(obj, firstName, lastName); // Bryan Smith just bought a Maserati from Italy
car.showBuyer.apply(obj, [firstName, lastName]); // Bryan Smith just bought a Maserati from Italy
간단한 예시를 알기 쉬운 평선으로 투고하고 싶기 때문에, 초보자도 알기 쉬운 것입니다.
func.call(context, args1, args2 ); // pass arguments as "," separated value
func.apply(context, [args1, args2]); // pass arguments as "Array"
또한 아래 코드에 정의된 참조 변경에는 "Call" 및 "Apply" 메서드를 사용합니다.
let Emp1 = {
name: 'X',
getEmpDetail: function(age, department) {
console.log(`Name: ${this.name} Age: ${age} Department: ${department}`)
}
}
Emp1.getEmpDetail(23, 'Delivery')
// 1st approach of changing "this"
let Emp2 = {
name: 'Y',
getEmpDetail: Emp1.getEmpDetail
}
Emp2.getEmpDetail(55, 'Finance')
// 2nd approach of changing "this" using "Call" and "Apply"
let Emp3 = {
name: 'Emp3_Object',
}
Emp1.getEmpDetail.call(Emp3, 30, 'Admin')
// here we have change the ref from **Emp1 to Emp3** object
// now this will print "Name = Emp3_Object" because it is pointing to Emp3 object
Emp1.getEmpDetail.apply(Emp3, [30, 'Admin'])
call()
된 함수를 합니다.this
값 및 인수를 개별적으로 제공합니다.
apply()
랑 비슷해요. - 이런 거랑 비슷해요.call()
의 첫 , " " "apply()
합니다.this
입니다.value : 수 value 、 함 value value value 。'아까운'입니다.obj
의 유일한 apply()
★★★★★★★★★★★★★★★★★」call()
은 '두 입니다.apply()
method는 실제 함수에 대한 인수를 배열로 받아들입니다.
언급URL : https://stackoverflow.com/questions/1986896/what-is-the-difference-between-call-and-apply
'itsource' 카테고리의 다른 글
Python에서 객체에 속성이 있는지 확인하려면 어떻게 해야 합니까? (0) | 2022.10.26 |
---|---|
열에서 고유한 값 선택 (0) | 2022.10.26 |
'/var/run/mysqld/mysqld 소켓을 통해 로컬 MySQL 서버에 연결할 수 없습니다.sock'(111 "Connection rejected"), (0) | 2022.10.26 |
Python에서 정수를 문자열로 변환 (0) | 2022.10.26 |
두 텍스트 문서 간의 유사성을 계산하는 방법은 무엇입니까? (0) | 2022.10.26 |