两个相似函数之间的区别,为什么一个有效而另一个无效

Difference between two similar functions, why is one working and the other not

本文关键字:一个 有效 另一个 无效 为什么 两个 相似 函数 区别 之间      更新时间:2023-09-26

我有两个函数,一个有效,另一个无效。

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

Uncaught TypeError: Cannot read property '0' of undefined

这是小提琴:

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();
        }

如何在不先将对象保存在局部变量中的情况下使第二个函数工作?我想尽可能使用双向数据绑定。

如何在不先将对象保存在局部变量中的情况下使第二个函数工作?

你不能。 this 是一个变量,它始终是使用它的函数的局部变量,其值取决于函数的调用方式。如果要在不同的函数中使用它的值,则需要将其复制到另一个变量中。

bind方法提供了执行此操作的简写。

setTimeout(delayedOutput.bind(this), 200);

简单的答案,你没有。由于您的函数是通过超时调用的,因此它不再位于同一上下文中,并且"this"将不再引用同一对象。

您可以这样做:

        loopThroughSplittedTextNotWorking: function() {
        // delete this
        var locationInString = 0;
        var that = this;
        function delayedOutput() {
            document.getElementById('output').innerHTML = that.splittedText[locationInString];
            locationInString++;
            if(locationInString < that.splittedText.length) {
                setTimeout(delayedOutput, 200);
            }
        }
        delayedOutput();
    }

通过将"this"变量保存到局部变量中,您可以在"delayedOutput"函数中访问它。

意识到这基本上就像你的工作示例一样,只是措辞有点不同,但通常这就是我的做法。