在JavaScript 中,this 引用会发生变化!
代码如下:
<html>
<head>
<title>this引用的更改</title>
<script type="text/javascript">
function changeThis() {
this.testValue = "this";
this.showValue = function() {
alert(this.testValue + ", " + this.value);
}
}
new changeThis().showValue();
</script>
</head>
<body>
<input type="button" id="btn" value="btn" />
<script type="text/javascript">
document.getElementById("btn").onclick = new changeThis().showValue;
</script>
</body>
</html>
一开始运行的弹出框显示的为“this, undefined”,但是你单击按钮之后却显示“undefined, btn”,说明this引用发生了变化!
原因:
由于document.getElementById("btn").onclick = new changeThis().showValue; 的定义,将onclick 事件定义为showValue 方法,因此当单击按钮时事件会调用showValue 方法。由于是事件调用方法,因此会在调用的方法中传入事件的调用者,即this 。它将改变原有的this 引用。因此引发了this 引用的变法,这可以认为是局部的this (事件对象)覆盖了全局this (function 方法)。
解决方案:
function changeThis() {
var self = this;
this.testValue = "this";
this.showValue = function() {
alert(self.testValue + ", " + self.value);
}
}
虽然这个错误我们很遇到的几率比较的小,但正因为如此当遇到时我们无法快速的发现和解决该错误。故特意列举出来为大家在今后的JavaScript 编程小心使用this 关键字。
代码如下:
<html>
<head>
<title>this引用的更改</title>
<script type="text/javascript">
function changeThis() {
this.testValue = "this";
this.showValue = function() {
alert(this.testValue + ", " + this.value);
}
}
new changeThis().showValue();
</script>
</head>
<body>
<input type="button" id="btn" value="btn" />
<script type="text/javascript">
document.getElementById("btn").onclick = new changeThis().showValue;
</script>
</body>
</html>
一开始运行的弹出框显示的为“this, undefined”,但是你单击按钮之后却显示“undefined, btn”,说明this引用发生了变化!
原因:
由于document.getElementById("btn").onclick = new changeThis().showValue; 的定义,将onclick 事件定义为showValue 方法,因此当单击按钮时事件会调用showValue 方法。由于是事件调用方法,因此会在调用的方法中传入事件的调用者,即this 。它将改变原有的this 引用。因此引发了this 引用的变法,这可以认为是局部的this (事件对象)覆盖了全局this (function 方法)。
解决方案:
function changeThis() {
var self = this;
this.testValue = "this";
this.showValue = function() {
alert(self.testValue + ", " + self.value);
}
}
虽然这个错误我们很遇到的几率比较的小,但正因为如此当遇到时我们无法快速的发现和解决该错误。故特意列举出来为大家在今后的JavaScript 编程小心使用this 关键字。