this概念:只要封装函数,任何一个函数系统都会内置一个叫做this的变量。
this变量存储的是地址,是当前函数主人的地址
【注】this永远指向当前函数的主人,函数的主人要通过当前上下文去判断
this类似于现实生活中,用到的“我”
<script>
var person = {
username: "眼前",
sex:"男",
show : function(){
alert(person.username);
alert(this.username);
}
};
person.show();
</script>
点击按钮,输出当前按钮的下标
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script>
window.onload = function(){
var aBtns = document.getElementsByTagName("button");
for(var i = 0;i < aBtns.length; i++){
//给每一个按钮添加一个自定义属性
aBtns[i].index = i;
aBtns[i].onclick = function(){
alert(this.index);
}
}
alert("循环结束了: "+ i);
}
</script>
</head>
<body>
<button>按钮1</button>
<button>按钮2</button>
<button>按钮3</button>
</body>
</html>