首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >理解jquery插件中的'this‘和'$(this)’

理解jquery插件中的'this‘和'$(this)’
EN

Stack Overflow用户
提问于 2014-01-13 12:56:56
回答 4查看 128关注 0票数 1
代码语言:javascript
运行
复制
var windw = this;
$.fn.followTo = function ( pos ) {
    var $this = this,$window = $(windw);
    $window.scroll(function(e){
        if ($window.scrollTop() > pos) {
            //if condition 
        } else {
            //else condition
        }
    });
};

在上面的代码中,我不能理解关于使用'this‘和'$(this)’的问题。

通过像这样修改代码,让我们看看我试图理解的内容:

代码语言:javascript
运行
复制
//var windw = this;
$.fn.followTo = function ( pos ) {
   // var $this = this,$window = $(windw); // as far as I understand $window becomes $(this)
    $(this).scroll(function(e){
        if ($(this).scrollTop() > pos) {
            //if condition
        } else {
            //else condition
        }
    });
};

我也尝试了这么多:

代码语言:javascript
运行
复制
//var windw = this;
$.fn.followTo = function ( pos ) {
   // var $this = this,
      //  $window = $(windw);
    this.scroll(function(e){
        if (this.scrollTop() > pos) { // also tried $(this) here
            //if condition
        } else {
            //else condition
        }
    });
};

糟了!这两个代码都不能工作!

有没有人能有更好的方法来澄清我关于第一个放置的代码是如何工作的概念?

EN

Stack Overflow用户

发布于 2014-01-13 13:26:57

在JavaScript中,“this”通常指的是“拥有”方法的对象,但这取决于函数的调用方式。

如果没有当前对象,‘this’指的是全局对象。在web浏览器中,这就是“窗口”--顶层对象,表示文档、位置、历史记录和其他一些有用的属性和方法。

当调用一个对象构造函数或它的任何方法时,‘this’指的是对象的实例-很像任何基于类的语言:

在你的代码中:

代码语言:javascript
运行
复制
var windw = this; // there’s no current object, ‘this’ refers to the global object. ie, window.

$.fn.followTo = function ( pos ) {
    // now this referes to the scope instance of $.fn.followTo which is not window
    var $this = this,$window = $(windw);
    $window.scroll(function(e){
        // inside this closure this referes to the instace of this closure function which is not window
        if ($window.scrollTop() > pos) {
            //if condition 
        } else {
            //else condition
        }
    });
};
票数 0
EN
查看全部 4 条回答
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/21084150

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档