0

可能重复:
Javascript 中的嵌套函数参数和“this”上下文

由于在嵌套类函数调用中使用“this”的问题,我目前无法根据需要设计我的 JS 类。不知道如何更好地描述它,所以这是我的意思的示例。

测试.html

<!DOCTYPE html>
<html class="main" lang="en">
<head>
    <meta charset="utf-8">
    <script type="text/javascript" src="test.js"></script>
    <script type="text/javascript">
        function doIt() {
            var myTestClass = new TestClass();
        }
    </script>
</head>
<body>
    <button onclick="doIt();">Do it!</button>
</body>
</html>

测试.js

function TestClass() {
   // this is working
   this.alertValue('This works');

   // this is not working
   setTimeout(function(){this.alertValue('This does not work!')}, 1000);
}

TestClass.prototype.alertValue = function(value) {
   alert('Value is: ' + value);
}

当然,这只是一个简化的示例来演示我的意思。那么如何在 setTimeout 调用内的函数中使用“this”标识符,或者如何更好/正确地实现这一目标?

非常感谢您提前提供的帮助!干杯

4

1 回答 1

5

将 的值保存this在变量 ( self) 中,然后您可以在 中访问它setTimeout

function TestClass() {
   this.alertValue('This works');
   var self = this;
   setTimeout(function() { 
     self.alertValue('This does not work!')
   }, 1000);
}
于 2012-08-22T11:24:05.327 回答