undefined

this指向及this应用

this

this可以理解为调用当前方法或者函数的那个对象,通俗地说就是谁调用了函数指的就是谁。例如下面程序的this指的是一个按钮。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
<!DOCTYPE HTML>
<html>

<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>无标题文档</title>
<script>
// this : 这个
// this: 指的是调用 当前 方法(函数)的那个对象

function fn1() {
// this
}
// fn1(); this => window
// oDiv.onclick = fn1; this => oDiv
/*
oDiv.onclick = function (){
fn1(); fn1() 里的this => window
};

<div onclick=" this fn1(); "></div> fn1(); 里的 this 指的是 window
*/
// alert( this ); // object window
// window 是 JS “老大”
// window.alert( this );

function fn1() {
alert(this); // window
}
// fn1();
// window.fn1();
</script>
</head>

<body>
<input id="btn1" type="button" value="按钮" />
<input id="btn2" type="button" onclick=" fn1(); " value="按钮2" />
<script>
var oBtn = document.getElementById('btn1');
// oBtn.onclick = fn1;
oBtn.onclick = function() {
// this
fn1();
};
</script>
</body>

</html>

觉得本站不错,请作者吃根辣条