javascript - 两个相似功能之间的区别,为什么一个有效而另一个无效

标签 javascript jquery loops vue.js

我有两个功能,一个有效,另一个无效。

它们是相等的,除了一个是循环遍历一个变量,其中保存了作用域的全局对象(希望这是有意义的),另一个尝试直接循环遍历文本,但失败了,因为它抛出错误:

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/

相关文章:

c# - 使用 C# 的先到先服务 (FCFS) CPU 调度错误

javascript - CKEDITOR 对 Bootstrap 表的支持

javascript - 如何将索引与 json 对象进行数据链接?

javascript - 数据未从 ajax POST 返回

c - 如何使用已经接受输入的单个 scanf 函数退出循环?

java - 为什么 FPS 不打印在我的窗口中?

php - 页面一直自动刷新

javascript - 遍历具有不同名称的表单字段

javascript - jQuery 快速问题

jQuery的append()和remove()元素