理解在timer.js中返回this

Understanding the return this in timer.js

本文关键字:返回 this js timer      更新时间:2023-09-26

我只是在浏览timer.js的代码,在Chrome中使用开发工具,基本上我这样调用插件:

var timer = $.timer(function(){
                $('#add-html').html('Hello There !!');    
            });

            timer.set({ time:5000 , autostart :true });

甚至演示也使用相同的示例,现在当下面的行执行时:

  var timer = $.timer(function(){
                    $('#add-html').html('Hello There !!');    
                });

插件内的这一行执行和returns this,但是此时return this是什么?它是整个插件的实例吗?或者它到底是什么,我知道没有它就会抛出错误,但是return this在这里到底是用来做什么的,它的value是什么?

我在JavaScript中使用return this进行链接等,但不知何故,我无法理解return this在这里的上下文用法。有人能解释一下吗?

您应该在调试器中运行此代码(设置断点或debugger语句),并在该点计算this

对于我来说,this === jQuery在第一次运行时为真,this instanceof $.timer在后续运行时为真。