js (JavaScript) 에서 call () 과 apply () 의 용법 을 읽 습 니 다.
자 바스 크 립 트 에서 함 수 는 대상 입 니 다.JavaScript 함 수 는 속성 과 방법 이 있 습 니 다.
call() 화해시키다 apply() 미리 정 의 된 함수 방법 입 니 다.두 가지 방법 은 함 수 를 호출 하 는 데 사용 할 수 있 으 며, 두 가지 방법의 첫 번 째 매개 변 수 는 반드시 대상 자체 여야 한다.
call
와 apply
함수 의 집행 환경, 즉 this
의 방향 을 재 정의 할 수 있다.call
와 apply
는 모두 특정한 함수 가 실 행 될 때의 context
, 즉 문맥 을 바 꾸 기 위해 존재 하 는 것 이다. 다시 말 하면 함수 체 내부 this
의 방향 을 바 꾸 기 위해 서 이다.문법
call()
한 대상 을 호출 하 는 방법 은 다른 대상 으로 현재 대상 을 교체 하면 다른 대상 의 속성 을 계승 할 수 있 습 니 다. 문법 은:
Function.call(obj[, param1[, param2[, [,...paramN]]]]);
obj
: 이 대상 은 Function
클래스 this
대상 params
: 매개 변수 목록 call
방법 은 다른 대상 을 대체 하여 하나의 방법 을 호출 할 수 있 습 니 다. call
방법 은 한 함수 의 대상 컨 텍스트 를 초기 컨 텍스트 에서 obj
지정 한 새로운 대상 으로 바 꿀 수 있 습 니 다. obj
인 자 를 제공 하지 않 으 면 Global 대상 은 obj
에 사 용 됩 니 다.<span style="color: #000000;">
window.color </span>= 'red'<span style="color: #000000;">;
document.color </span>= 'yellow'<span style="color: #000000;">;
</span><span style="color: #0000ff;">var</span> s1 = {color: 'blue'<span style="color: #000000;"> };
</span><span style="color: #0000ff;">function</span><span style="color: #000000;"> changeColor(){
console.log(</span><span style="color: #0000ff;">this</span><span style="color: #000000;">.color);
}
changeColor.call(); </span><span style="color: #008000;">//</span><span style="color: #008000;">red ( )</span>
changeColor.call(window); <span style="color: #008000;">//</span><span style="color: #008000;">red</span>
changeColor.call(document); <span style="color: #008000;">//</span><span style="color: #008000;">yellow</span>
changeColor.call(<span style="color: #0000ff;">this</span>); <span style="color: #008000;">//</span><span style="color: #008000;">red</span>
changeColor.call(s1); <span style="color: #008000;">//</span><span style="color: #008000;">blue</span>
// 2
var Pet = {
words : '...',
speak : function (say) {
console.log(say + ''+ this.words)
}
}
Pet.speak('Speak'); // :Speak...
var Dog = {
words:'Wang'
}
// this Dog
Pet.speak.call(Dog, 'Speak'); // : SpeakWang
apply()
call()
방법 과 마찬가지 로 매개 변수 목록 만 다 릅 니 다. 문법:Function.apply(obj[, argArray]);
obj
: 이 대상 은 Function
클래스 this
대상 argArray
: 이것 은 배열 입 니 다. 매개 변수 로 Function
설명:
argArray
유효한 배열 이 아니 거나 arguments
대상 이 아니라면 TypeError
하 나 를 초래 할 수 있 습 니 다. argArray
와 obj
어떠한 인자 도 제공 하지 않 으 면 Global 대상 은 obj
으로 사 용 됩 니 다.<span style="color: #000000;">
window.number </span>= 'one'<span style="color: #000000;">;
document.number </span>= 'two'<span style="color: #000000;">;
</span><span style="color: #0000ff;">var</span> s1 = {number: 'three'<span style="color: #000000;"> };
</span><span style="color: #0000ff;">function</span><span style="color: #000000;"> changeColor(){
console.log(</span><span style="color: #0000ff;">this</span><span style="color: #000000;">.number);
}
changeColor.apply(); </span><span style="color: #008000;">//</span><span style="color: #008000;">one ( )</span>
changeColor.apply(window); <span style="color: #008000;">//</span><span style="color: #008000;">one</span>
changeColor.apply(document); <span style="color: #008000;">//</span><span style="color: #008000;">two</span>
changeColor.apply(<span style="color: #0000ff;">this</span>); <span style="color: #008000;">//</span><span style="color: #008000;">one</span>
changeColor.apply(s1); <span style="color: #008000;">//</span><span style="color: #008000;">three</span>
// 2
function Pet(words){
this.words = words;
this.speak = function () {
console.log( this.words)
}
}
function Dog(words){
//Pet.call(this, words); // : Wang
Pet.apply(this, arguments); // : Wang
}
var dog = new Dog('Wang');
dog.speak();
2. 공통점
call()
과 apply()
방법의 공통점 은 바로 이 두 방법의 작용 이 같다 는 것 이다.모두 특정한 역할 영역 에서 함 수 를 호출 하 는 것 은 함수 체 내 this
대상 의 값 을 설정 하여 함수 가 실행 하 는 역할 영역 을 확장 하 는 것 과 같다.일반적으로
this
는 특정한 방법 을 호출 하 는 대상 을 가리 키 지만 call()
과 apply()
방법 을 사용 할 때 this
의 방향 이 바 뀌 어 예 를 들 어:function add(a, b) {
return a + b;
}
function sub(a, b) {
return a - b;
}
add.call(sub, 2, 1); //3
왜
add.call(sub, 2, 1)
의 집행 결 과 는 3
일 까? call()
방법 이 this
의 방향 을 바 꾸 었 기 때문에 sub
호출 add
방법, 즉 sub
으로 집행 add
중의 내용 을 다시 한 번 예 를 들 어 보 자.function People(name, age) {
this.name = name;
this.age = age;
}
function Student(name, age, grade) {
People.call(this, name, age);
this.grade = grade;
}
var student = new Student(' ', 21, ' ');
console.log(student.name + student.age + student.grade);// 21
이 예 에서 우 리 는
Student
의 name
와 age
에 값 을 부여 하지 않 았 지만 이 두 속성의 값 이 존재 한다. 이것 은 call()
방법 에 의 해 바 뀔 수 있다 this
의 방향 을 바 꿀 수 있다.이 예 에서 People.call(this, name, age);
중의 this
은 Student
를 대표 한다. 이것 은 바로 앞에서 말 한 것 으로 Student
에서 People
중의 방법 을 호출 할 수 있 게 하 는 것 이다. People
에 this.name = name;
등 문구 가 있 기 때문에 name
와 age
속성 을 Student
에 만 들 었 다.한 마디 로
call()
괄호 안의 대상 으로 하여 금 괄호 외 함수 의 속성 을 계승 하 게 할 수 있다.apply()
방법의 작용 도 call()
방법 과 마찬가지 로 이렇게 쓸 수 있다.People.apply(this, [name, age]);
아니면 이렇게 쓰 세 요.
People.apply(this, arguments);
여기 서
arguments
와 [name, age]
는 등가 이다.3. 차이 점
정의 에서 도 알 수 있 듯 이
call()
과 apply()
의 차이 점 은 바로 파 라 메 터 를 받 는 방식 이 다르다 는 것 이다.this
이 고 다른 하 나 는 매개 변수 배열 입 니 다.this
이지 만 함수 에 전달 하 는 인 자 는 반드시 열거 해 야 한다.대상 에 게 매개 변 수 를 주 는 상황 에서 매개 변수의 형식 이 배열 일 때 예 를 들 어 이전
apply()
방법 예제 에서 매개 변수 arguments
를 전달 했다. 이 매개 변 수 는 배열 유형 이 고 호출 Person
할 때 매개 변수의 목록 은 일치 하 는 것 (즉 Person
과 Student
의 매개 변수 목록 앞 두 자리 가 일치 하 는 것) 을 사용 하면 apply()
방법 을 사용 할 수 있다.그러나
Person
의 매개 변수 목록 이 이러한 (age,name)
이 고 Student 의 매개 변수 목록 이 (name,age,grade)
이 라면 call()
방법 으로 이 루어 질 수 있다. 즉, 매개 변수 목록 의 대응 치 위 치 를 직접 지정 하 는 것 Person.call(this,age,name)
이다.4. 어떤 상황 에서 apply 를 사용 하고 어떤 상황 에서 call 을 사용 합 니까?
대상 에 게 매개 변 수 를 주 는 상황 에서 매개 변수의 형식 이 배열 일 때, 예 를 들 어 apply 예제 에서 매개 변수 arguments 를 전 달 했 습 니 다. 이 매개 변 수 는 배열 형식 이 고 Person 을 호출 할 때 매개 변수의 목록 이 일치 합 니 다 (즉, Person 과 Student 의 매개 변수 목록 앞 두 자리 가 일치 합 니 다). apply 를 사용 할 수 있 습 니 다. 만약 에 제 Person 의 매개 변수 목록 이 이런 것 이 라면.(age, name), Student 의 매개 변수 목록 은 (name, age, grade) 입 니 다. 그러면 call 로 이 루어 집 니 다. 즉, 매개 변수 목록 에 대응 하 는 값 의 위 치 를 직접 지정 하 는 것 입 니 다 (Person. call (this, age, name, grade).
<span style="color: #008000;">/*</span><span style="color: #008000;"> </span><span style="color: #008000;">*/</span>
<span style="color: #0000ff;">function</span><span style="color: #000000;"> Person(name,age)
{
</span><span style="color: #0000ff;">this</span>.name=<span style="color: #000000;">name;
</span><span style="color: #0000ff;">this</span>.age=<span style="color: #000000;">age;
}
</span><span style="color: #008000;">/*</span><span style="color: #008000;"> </span><span style="color: #008000;">*/</span><span style="color: #000000;">
functionStudent(name,age,grade)
{
Person.apply(</span><span style="color: #0000ff;">this</span>,arguments); <span style="color: #008000;">//</span><span style="color: #008000;">Person.call(this,name,age);</span>
<span style="color: #0000ff;">this</span>.grade=<span style="color: #000000;">grade;
}
</span><span style="color: #008000;">//</span><span style="color: #008000;"> </span>
<span style="color: #0000ff;">var</span> student=<span style="color: #0000ff;">new</span> Student("zhangsan",21," "<span style="color: #000000;">);
</span><span style="color: #008000;">//</span><span style="color: #008000;"> </span>
alert("name:"+student.name+"
"+"age:"+student.age+"
"+"grade:"+<span style="color: #000000;">student.grade);
</span><span style="color: #008000;">//</span><span style="color: #008000;"> name:zhangsan age:21 grade: </span>
<span style="color: #008000;">//</span><span style="color: #008000;"> name age , , apply . </span>
5. 확장
apply () 의 기타 용법
apply
교묘 한 용도 가 있 습 니 다. 한 배열 의 기본 값 을 하나의 매개 변수 목록 [param1,param2,param3]
으로 전환 할 수 있 습 니 다. param1,param2,param3
의 이러한 특성 을 통 해 다음 과 같은 효율 적 인 방법 이 있 습 니 다.1) Math. max 는 배열 에서 가장 큰 것 을 얻 을 수 있다.
apply
매개 변수 에 지원 되 지 않 기 때문에 Math.max
, 즉 배열 이지 만 지원 Math.max([param1,param2])
하기 때문에 Math.max(param1,param2,param3…)
의 그 특징 에 따라 해결 할 수 있 습 니 다.var array = [1, 2, 3];
var max = Math.max.apply(null, array);
console.log(max);//3
이렇게 하면 한 배열 에서 가장 큰 하 나 를 쉽게 얻 을 수 있 습 니 다.
apply
한 배열 을 하나의 매개 변수 와 하나의 매개 변 수 를 연결 하 는 전달 방법 으로 바 꿀 것 입 니 다. 이 매개 변 수 는 호출 할 때 첫 번 째 매개 변 수 를 하나 apply
주 었 습 니 다.이것 은 대상 이 이 방법 을 호출 하지 않 기 때문에 우 리 는 이 방법 으로 나 를 도와 연산 을 하고 되 돌아 오 는 결 과 를 얻 으 면 되 기 때문에 하나의 null
과 거 를 직접 전달 했다. 물론 첫 번 째 매개 변 수 는 사용 null
해도 된다.var array = [1, 2, 3];
var max = Math.max.apply(this, array);
console.log(max);//3
사용
this
은 전체 대상 으로 호출 this
하 는 것 과 같 기 때문에 마찬가지 입 니 다.2) Math. min 은 배열 에서 가장 작은 것 을 얻 을 수 있다.
같은
Math.max
과 Math.min
는 하나의 사상 이다.var array = [1, 2, 3];
var min = Math.min.apply(null, array);
console.log(min);//1
물론
Math.max
의 첫 번 째 매개 변 수 는 apply
도 사용 할 수 있 고 null
도 사용 할 수 있 으 며 이것 은 this
과 같다.3) Array. prototype. push 는 두 배열 의 합병 을 실현 할 수 있다.
마찬가지 로
Math.max
방법 은 push
하나의 배열 을 제공 하지 않 았 지만 push
을 제공 하기 때문에 push(param1,param,…paramN)
을 통 해 이 배열 을 바 꿀 수 있다. 즉,:var arr1 = [1, 2, 3];
var arr2 = [4, 5, 6];
Array.prototype.push.apply(arr1, arr2);
console.log(arr1);//[ 1, 2, 3, 4, 5, 6 ]
이렇게 이해 할 수 있다.
apply
는 arr1
의 Array
방법 을 호출 했다. 매개 변 수 는 push
배열 을 매개 변수 목록 의 집합 으로 바 꾸 는 것 이다. 사실은 apply
도 자신의 arr1
방법 을 호출 할 수 있다.var arr1 = [1, 2, 3];
var arr2 = [4, 5, 6];
arr1.push.apply(arr1, arr2);
console.log(arr1);//[ 1, 2, 3, 4, 5, 6 ]
즉,
push
방법 만 있 으 면 push
방법 으로 이 방법 을 호출 할 수 있 고 arr1
방법 으로 배열 을 일련의 매개 변수 로 전환 할 수 있 기 때문에 이렇게 쓸 수 있다.var arr1 = [1, 2, 3];
var arr2 = [4, 5, 6];
[].push.apply(arr1, arr2);
console.log(arr1);//[ 1, 2, 3, 4, 5, 6 ]
총결산
일반적으로 목표 함수 에 서 는 n 개의 매개 변수 목록 만 필요 하지만 한 배열 의 형식
apply
을 받 지 않 으 면 우 리 는 apply
방식 으로 교묘 하 게 해결 할 수 있다.
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
다양한 언어의 JSONJSON은 Javascript 표기법을 사용하여 데이터 구조를 레이아웃하는 데이터 형식입니다. 그러나 Javascript가 코드에서 이러한 구조를 나타낼 수 있는 유일한 언어는 아닙니다. 저는 일반적으로 '객체'{}...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.