使用'这'在类中的嵌套函数中
Using 'this' in nested function in class
可能重复:
嵌套的函数参数和';这';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);
}
相关文章:
- 用嵌套函数和默认函数定义函数
- d3中堆栈函数和嵌套函数之间的差异
- JavaScript 中的嵌套函数和 “this” 关键字
- 嵌套到另一个函数中的Fancybox函数;不起作用
- Javascript中带有返回值的嵌套函数
- 访问嵌套函数结构中的JavaScript父函数变量
- 从嵌套函数访问函数属性
- 如何在javascript中使用嵌套函数作为生成器(使用“inner”yields)
- Javascript嵌套函数属性继承
- 具有嵌套对象数组的 Javascript 对象的递归搜索函数
- Facebook Javascript 函数嵌套循环
- 将动态 AJAX 函数嵌套在 JavaScript 函数中 - 并保持更新
- 对由多个groupBy函数嵌套的对象数组进行分组
- 从父函数返回什么以获取从子函数/嵌套函数返回的值
- jQuery匿名函数-嵌套函数
- ajax调用函数嵌套
- 函数嵌套括号的Python风格指南是什么?
- setTimeout函数中的关键字,该函数嵌套在on()方法下.但这并没有奏效
- 嵌套异步函数嵌套同步函数
- 如何克服函数嵌套