为什么这样做而不是jQuery插件中的$(this) [英] Why this and not $(this) in jQuery plugins

查看:82
本文介绍了为什么这样做而不是jQuery插件中的$(this)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

文档告诉我们:

假设我们要创建一个插件,该插件可以在一组 检索到的元素为绿色.我们要做的就是添加一个名为 绿色化为$ .fn,它将像任何其他jQuery一样可用 对象方法.

Let's say we want to create a plugin that makes text within a set of retrieved elements green. All we have to do is add a function called greenify to $.fn and it will be available just like any other jQuery object method.

$.fn.greenify = function() {
    this.css( "color", "green" );
};


$( "a" ).greenify(); // Makes all the links green.

请注意,我们要使用.css(),而不是$(this).这是因为我们的绿色化功能是同一对象的一部分 为.css().

Notice that to use .css(), another method, we use this, not $( this ). This is because our greenify function is a part of the same object as .css().

我不明白最后一段.该函数传递给this的什么?为什么不$(this)引用jQuery对象?我们不使用$(el).css()通常在jQuery中设置CSS吗?那为什么不在插件中呢?

I don't understand that last paragraph. What does the function pass to this? Why not $(this) to refer to the jQuery object? Don't we use $(el).css() to normally set CSS in jQuery? Then why not within a plugin?

推荐答案

让我们尝试更深入一点:

Let's try see a bit deeper:

让我们尝试生成一个非常简化的版本库,例如jQuery,并将其命名为 microM

let's try generate a very simplified version lib, like jQuery, and name it for example microM

(function(global) {
  //function analog jQuery
  var microM = function(context) { 
    return new microM.fn.init(context);
  }

  //init prototype
  microM.fn = microM.prototype = {
    version: '0.0.0.1',
    constructor: microM
  };

  //function for initialize context
  var init = microM.fn.init = function(context) {
    if (context instanceof microM) context = microM.extend([], context.context);

    this['context'] = [].concat(context);
    return this;
  };

  init.prototype = microM.fn;

  //add function extend to prototype and as static method
  microM.extend = microM.fn.extend = function() {
    if (arguments.length == 2) {
      var target = arguments[0],
        source = arguments[1];
    } else {
      var target = this,
        source = arguments[0];
    }
    for (var key in source) {
      target[key] = source[key];
    }

    return target;
  }

  //extend microM prototype with a few simple function
  microM.fn.extend({
    min: function() {
      return Math.min.apply(Math, this.context);
    },
    max: function() {
      return Math.max.apply(Math, this.context);
    },
    pow: function(exponent) {
      for (var i = 0, len = this.context.length; i < len; i++) {
        this.context[i] = Math.pow(this.context[i], exponent);
      }
      return this;
    },
    get: function() {
      return microM.extend([], this.context);
    },
    map: function(callback) {//a function that takes a callback
      var result = [];
      for (var i = 0, len = this.context.length; i < len; i++) {
        var callbackResult = callback.call(this.context[i], this.context[i], i);
        if (callbackResult instanceof microM) result = result.concat(callbackResult.get());
        else result = result.concat(callbackResult);
      }
      return microM(result);
    }
  });

  //looks a like jQuery :-)
  global.microM = microM;
})(window);

所以我们有一个最简单的库,看起来像jQuery.现在,我们要向其中添加插件",例如函数 square .

So we have a simplest lib looks a like jQuery. Now we want add "plugin" to it, for example function square.

就像在jQuery中一样,我们将其添加到原型中,或者将 fn 添加到我们的示例中:

As in jQuery we add this to prototype, or fn that same as prototype in our case:

microM.fn.square = function() {
  return this.pow(2);
}

在这里我们可以直接从 this 调用 pow ,因为在这种情况下,我们的 microM this 实例,以及 microM.prototype 中的所有功能都可以直接使用;

here we can call pow directly from this because in this case this instance of our microM, and all functions from microM.prototype is available directly;

但是当我们调用 map 函数时,该函数需要在回调内进行回调.

But when we call our map function that takes a callback inside callback this will be concrete element, for example Number primitive, because we call it like

callback.call(this.context[i], this.context[i], i);

调用函数 -是 thisArg .

下面的可能的代码片段可以使我的解释更加混乱:-)

Possibly code snippet below can make clear my muddled explanation :-)

(function(global) {
  var microM = function(context) {
    return new microM.fn.init(context);
  }

  microM.fn = microM.prototype = {
    version: '0.0.0.1',
    constructor: microM
  };

  var init = microM.fn.init = function(context) {
    if (context instanceof microM) context = microM.extend([], context.context);

    this['context'] = [].concat(context);
    return this;
  };

  init.prototype = microM.fn;

  microM.extend = microM.fn.extend = function() {
    if (arguments.length == 2) {
      var target = arguments[0],
        source = arguments[1];
    } else {
      var target = this,
        source = arguments[0];
    }
    for (var key in source) {
      target[key] = source[key];
    }

    return target;
  }

  microM.fn.extend({
    min: function() {
      return Math.min.apply(Math, this.context);
    },
    max: function() {
      return Math.max.apply(Math, this.context);
    },
    pow: function(exponent) {
      for (var i = 0, len = this.context.length; i < len; i++) {
        this.context[i] = Math.pow(this.context[i], exponent);
      }
      return this;
    },
    get: function() {
      return microM.extend([], this.context);
    },
    map: function(callback) {
      var result = [];
      for (var i = 0, len = this.context.length; i < len; i++) {
        var callbackResult = callback.call(this.context[i], this.context[i], i);
        if (callbackResult instanceof microM) result = result.concat(callbackResult.get());
        else result = result.concat(callbackResult);
      }
      return microM(result);
    }
  });

  global.microM = microM;
})(window);


microM.fn.printTo = function(id, descr) {
  document.getElementById(id).innerHTML += (descr ? descr + ": " : "") + JSON.stringify(this.get()) + '<br/>';
  return this;
}

microM.fn.square = function() {
  return this.pow(2);
}

var t = microM([2, 3, 4]).printTo('res', 'initial');
t.square().printTo('res', 'square')
  .map(function(el) {
    return microM(this + 10).square();
  }).printTo('res', 'mapped')
  .map(function(el) {
    return this instanceof Number;
  }).printTo('res', 'inside map: this instanceof Number');

<div id="res"></div>

这篇关于为什么这样做而不是jQuery插件中的$(this)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆