jquery之$.proxy()

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8" />
	<title>$.proxy()的使用</title>
	<script type="text/javascript" src="jquery.min.js"></script>
</head>
<body>
	<input type="button" value="測試" id="myBtn" name="我的按鈕"/>
	<script type="text/javascript">
	// 定義一個對象,含有屬性name和一個sayHello的方法
	var hbk = {
		name:"huangbaokang",
		sayHello:function(){
			alert("hello "+this.name);
		}
	}

	//$("#myBtn").click(hbk.sayHello);// hello 我的按鈕
	// 如果想輸出hbk對象的name
	//$("#myBtn").click($.proxy(hbk.sayHello,hbk)); // hello huangbaokang
	// 另外一種用法
	$("#myBtn").click($.proxy(hbk,"sayHello")); // hello huangbaokang

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

$.proxy()方法主要是修改this指針的指向。
他有兩種使用方法。
$.proxy(a,b)
第一種:a是一個function函數,b是這個函數的對象所有者.
第二種:a是一個對象,b是一個字符串,是a的屬性名.
從源碼中也可以看到。
在這裏插入圖片描述
案列1:

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8" />
	<title>$.proxy()的使用</title>
	<script type="text/javascript" src="jquery.min.js"></script>
</head>
<body>
	<div id="panel" style="display: none;">
		<button>關閉</button>
	</div>
	<script type="text/javascript">
		/*$("#panel").fadeIn(function(){
			$("#panel button").click(function(){
				$(this).fadeOut();   // 這種方式panel並沒有設置display:none
			});
		});*/

		$("#panel").fadeIn(function () {
			$("#panel button").click($.proxy(function () {
				$(this).fadeOut();
			}, this));
		});
	</script>
</body>
</html>

案例2:

//正常的this使用
$('#Haorooms').click(function() {
 
  // 這個this是我們所期望的,當前元素的this.
 
  $(this).addClass('aNewClass');
 
});
//並非所期望的this
$('#Haorooms').click(function() {
 
  setTimeout(function() {
 
     // 這個this指向的是settimeout函數內部,而非之前的html元素
 
    $(this).addClass('aNewClass');
 
  }, 1000);
 
});

這時候怎麼辦呢,通常的一種做法是這樣的:

$('#Haorooms').click(function() {
  var that = this;  //設置一個變量,指向這個需要的this
 
  setTimeout(function() {
 
     // 這個this指向的是settimeout函數內部,而非之前的html元素
 
    $(that).addClass('aNewClass');
 
  }, 1000);
 
});

也可以使用jquery爲我們提供的proxy方法

$('#Haorooms').click(function() {
 
  setTimeout($.proxy(function() {
 
    $(this).addClass('aNewClass'); 
 
  }, this), 1000);
 
});
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章