由于在嵌套类函数调用中使用“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”标识符,或者如何更好/正确地实现这一目标?
非常感谢您提前提供的帮助!干杯