我有两个功能,一个有效,另一个无效。
它们是相等的,除了一个是循环遍历一个变量,其中保存了作用域的全局对象(希望这是有意义的),另一个尝试直接循环遍历文本,但失败了,因为它抛出错误:
Uncaught TypeError: Cannot read property '0' of undefined
这是 fiddle :
http://jsfiddle.net/4p1p4wjy/2/
据我了解,该函数的第二个版本不起作用,因为它无法从函数的回调中访问 this.splittedText
。
第一个工作功能:
loopThroughSplittedText: function() {
// delete this
var locationInString = 0;
var splittedText = this.splittedText;
function delayedOutput() {
document.getElementById('output').innerHTML = splittedText[locationInString];
locationInString++;
if(locationInString < splittedText.length) {
setTimeout(delayedOutput, 200);
}
}
delayedOutput();
},
第二个不起作用的功能:
loopThroughSplittedTextNotWorking: function() {
// delete this
var locationInString = 0;
function delayedOutput() {
document.getElementById('output').innerHTML = this.splittedText[locationInString];
locationInString++;
if(locationInString < this.splittedText.length) {
setTimeout(delayedOutput, 200);
}
}
delayedOutput();
}
如何使第二个函数工作,而不先将对象保存在局部变量中?我想尽可能地使用双向数据绑定(bind)。
最佳答案
How do I make the 2nd function work, without saving the object inside a local variable first?
你不能。 this
是一个变量,始终是其所用函数的本地变量,其值取决于函数的调用方式。如果您想在不同的函数中使用它的值,那么您需要将其复制到另一个变量中。
bind
方法提供了执行此操作的简写方法。
setTimeout(delayedOutput.bind(this), 200);
关于javascript - 两个相似功能之间的区别,为什么一个有效而另一个无效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30898780/