Javascript 학습 노트 의 apply 와 call 방법

1822 단어 JavaScripthtmlXHTML
apply 방법 과 call 방법 은 함 수 를 다른 대상 에 연결 하여 실행 할 수 있 습 니 다. 호출 매개 변수 형식 이 다 르 기 때문에 apply 방법 은 배열 형식 으로 함수 의 호출 매개 변 수 를 전달 하고 call 방법 은 쉼표 로 구 분 된 매개 변수 목록 을 사용 합 니 다.예 를 들 어 obj 1. methodA. apply (obj 2, ["호출 methodA"]);obj 1 의 methodA 방법 을 대상 obj 2 에 연결 하여 실행 하 는 것 을 표시 합 니 다.
 
예시:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<title>     </title>
</head>
<script language="javascript">
<!--	

		function ClassA(){
				this.className= "classA";
				this.methodA = function(msg){
				document.writeln(this.className+" : "+ msg+"<br>");
			}
		}
		function ClassB(){
				this.className= "classB";
				this.methodB = function(msg){
				document.writeln(this.className+" : "+msg+"<br>");
			}
		}
	
	var obj1 = new ClassA();
	var obj2 = new ClassB();
	
	obj1.methodA("  methodA");
	obj2.methodB("  methodB");
	
	obj1.methodA.apply(obj2, ["  methodA"]);
	obj2.methodB.apply(obj1, ["  methodB"]);
	obj1.methodA.call(obj2, "  methodA");
	obj2.methodB.call(obj1, "  methodB");

-->
</script>
<body >
</body>
</html>

 
출력 결 과 는:
 
classA: 호출 methodAclassB: 호출 methodBclassB: 호출 methodAclassA: 호출 methodBclassB: 호출 methodAclassA: 호출 methodB

좋은 웹페이지 즐겨찾기