0

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

4

3 回答 3

3

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

于 2013-03-29T21:46:04.683 回答
1

Yes, this keyword in JavaScript still means the element in the current scope.

于 2013-03-29T21:56:09.330 回答
0

Short explanation: this is the context of a function that can change depending on how that function is called. For example:

function myfunc() {
  console.log(this.toString());
}

myfunc(); //=> [object Window] 
myfunc.call('Hello World'); //=> Hello World

When using prototypes, this refers to the current instance. In jQuery it works something like this (very simplified):

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

So when you do this $(this) you're just creating a new jQuery instance of whatever this refers to (usually a DOM element) so you can inherit the prototype and use the public methods.

于 2013-03-29T21:57:32.280 回答