js中方法的行內綁定和動態綁定的區別
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
</head>
<body>
<div id="mydiv">aaaaa</div>
<div id="mydiv1" onclick="test();">bbbbb</div>
<div id="mydiv2" onclick="test2(this);">bbbbb</div>
</body>
<script type="text/javascript" >
document.getElementById('mydiv').onclick=test1;
//相當于 對象.屬性=test1,相當于對象擁有了test1屬性,this指向當前對象
function test1(){
this.style.color='red';
}
function test(){
this.style.color='red';
}
function test2(t){
t.style.color='red';
}
//1.我們在js定義的所有的全局變量 和方法,都是需要附屬在window上的,當成window的屬性,所以在test方法中的
//this指向window,不是當前元素,所以test方法執行報錯。在js中,規定,函數被哪個元素調用,this指向這個元素。
//當方法被動態綁定時,是當前元素調用方法,當行內綁定時,如果不在方法中傳入當前對象,方法中的this指向window。
</script>
</html>