【问题标题】:"This" keyword in javascript & jQuery [duplicate]javascript和jQuery中的“This”关键字[重复]
【发布时间】:2013-03-20 15:57:52
【问题描述】:

我目前正在学习 jQuery,并且刚刚开始实现 "this" 关键字。我了解它在 jQuery 中的作用,但它在 javascript 中是否具有与作用域引用相同的功能?

【问题讨论】:

标签: javascript jquery


【解决方案1】:

this 不是什么 jQuery 魔法,它是一个 JavaScript 关键字。

【讨论】:

  • 我就是这么想的,谢谢你的澄清。
  • 只是好奇,this到底可以用来做什么?有时我尝试实现它,但发现它返回错误的值/变量/元素。
  • 虽然这可能并不神奇 - 我认为它非常神奇,尤其是当 var that = this;
【解决方案2】:

是的,JavaScript 中的this 关键字仍然表示当前范围内的元素。

【讨论】:

    【解决方案3】:

    简短的解释:this 是一个函数的上下文,它可以根据调用该函数的方式而改变。例如:

    function myfunc() {
      console.log(this.toString());
    }
    
    myfunc(); //=> [object Window] 
    myfunc.call('Hello World'); //=> Hello World
    

    使用原型时,this 指的是当前实例。在 jQuery 中,它的工作原理是这样的(非常简化):

    (function(win) {
    
      // Constructor
      function jQuery(selector) {
    
      }
    
      // Shortcut to create news instances
      function $(selector) {
        return new jQuery(selector);
      }
    
      // Public methods
      jQuery.prototype = {
    
        // All methods 'return this' to allow chaining
        // 'this' is the jQuery instance
        method: function() {
          return this;
        }
    
      };
    
      win.$ = $; // expose to user
    
    }(window));
    

    因此,当您这样做 $(this) 时,您只是创建了一个新的 jQuery 实例,该实例包含 this 所指的任何内容(通常是一个 DOM 元素),因此您可以继承原型并使用公共方法。

    【讨论】:

      猜你喜欢
      • 2019-11-18
      • 2018-09-26
      • 2016-05-16
      • 1970-01-01
      • 1970-01-01
      • 2020-01-27
      • 2019-11-20
      • 1970-01-01
      • 2020-06-21
      相关资源
      最近更新 更多