使用'这'在类中的嵌套函数中

Using 'this' in nested function in class

本文关键字:函数 嵌套 使用      更新时间:2023-09-26

可能重复:
嵌套的函数参数和';这';Javascript 中的上下文

由于在嵌套类函数调用中使用"this"的问题,我目前在根据需要设计JS类时遇到了问题。不知道如何更好地描述它,所以这里有一个我的意思的例子。

test.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>

test.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"标识符,或者如何更好/正确地实现这一点呢?

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

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

function TestClass() {
   this.alertValue('This works');
   var self = this;
   setTimeout(function() { 
     self.alertValue('This does not work!')
   }, 1000);
}