1. 程式人生 > >bind()方法複製函式或者方法,理解this不同作用域下的指代問題

bind()方法複製函式或者方法,理解this不同作用域下的指代問題

要點:

1.用法:函式名(方法名).call(物件,引數1,引數2),來複制函式或者方法的名字。

2.這個例子中,引數隨機數,只在建構函式例項化的時候,建立rm例項物件時呼叫一次,定時器中呼叫的是函式的顯示方法。

3.理解bind方法前後this指代不同的原因,看註釋。

程式碼:

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>Document</title>
</head>
<body>
	<script type="text/javascript">
		function CreateRandom(){
			this.number = parseInt(Math.random() * 10 + 1);
		}
		// 

		CreateRandom.prototype.show1 = function(){
            window.setInterval(this.show2.bind(this),1000);
            // show2方法中的列印語句指代的原來是呼叫定時器的物件window,
            // 通過bind()方法傳入的this,指代當前的呼叫的bind方法的CreateRandow物件
            // show2前面的this指代的是window,後面的this指代的是CreateRandow注意理解作用域

            // console.log(this);
            // 通過這句可以測試這裡的this指向
		}  
		CreateRandom.prototype.show2 = function(){
			console.log(this.number);
		}

		var sr = new CreateRandom();
		sr.show1(); 

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

結果;