每个函数中的“this”都没有指向.each的调用者

时间:2014-09-08 15:43:28

标签: javascript class joomla mootools

在jQuery中,

$('.myClass').each(function(){return this;})

将使用类.myClass重新启动每个元素。我想这也是mootools的每个函数的情况。但是,当我尝试阅读以下代码时,我感到困惑(' attach'函数是有问题的方法,因此您可以跳过其他代码):

var Mosaic = new Class({

        Implements: //some codes,

        options: //some codes

        initialize: function(options){
            this.setOptions(options);

            this.mosaics = document.getElements('[data-mosaic]');
            this.mosaic = {};
            this.settings = {};
            try {
                RokMediaQueries.on('every', this.mediaQuery.bind(this));
            }
            catch(error) { if (typeof console != 'undefined') console.error('Error while trying to add a RokMediaQuery "match" event', error); }
        },

        attach: function(mosaic, settings){
            mosaic = typeOf(mosaic) == 'number' ?
                    document.getElements('[data-mosaic=' + this.getID(mosaic) + ']')
                    :
                    mosaic;
            settings = typeOf(settings) == 'string' ? JSON.decode(settings) : settings;

            var containers = (mosaic ? new Elements([mosaic]).flatten() : this.mosaics);

            containers.each(function(container){
                container.store('roksprocket:mosaic:attached', true);
                this.setSettings(container, settings, 'restore');
                // ..... 

        setSettings: //some functions
        // .....
    });

在'附加'方法,有一个容器调用,其中'这个'并没有指向'容器的当前元素,而是指向通过Mosaic CLass创建的实例。在代码的某处,有类似的东西:

myDemonstrate = new Mosaic();
myDemonstrate.attach(somekey, someJson);

我在线上设置了一个断点

this.setSettings(container, settings, 'restore');

此时,"这个"实际上是对象myDemonstrate。

那么,为什么"这个"这里不是.each函数的调用者?它是否与Mosaic()函数内部有关吗?

(RokSprocketMosaic是由RocketTheme开发的joomla扩展,如果需要,你可以在这里找到Mosaic.js文件:http://fbnychoir.org/components/com_roksprocket/layouts/mosaic/themes/default/mosaic.js

2 个答案:

答案 0 :(得分:3)

MooTools .each()迭代器的行为类似于ES5' .forEach(),即它会将数组元素和resp索引传递给函数。 this对应于执行上下文,或者可以通过将bind参数传递给方法来设置。

作为@DimitarChristoff refered in the comments,如果未提供bind参数,则this将取决于您的文档标准模式 - 严格为global objectundefined模式。下。

the docs at mootools.net的异常:

数组方法:each()

为数组中的每个元素调用一个函数。

语法:

myArray.each(fn[, bind]);

参数:

  1. fn - ( function )应该对数组中的每个项执行的函数。该函数在数组中传递项及其索引。
  2. bind - ( object ,optional)要用作' this'在功能中。有关更多信息,请参阅[功能:绑定] []。
  3. 参数:fn

      

    语法:fn(项目,索引,数组)

    参数:
    1. item - ( mixed )数组中的当前项。
    2. index - ( number )数组中当前项的索引。
    3. array - ( array )实际数组。
    4. 示例:

      //Alerts "0 = apple", "1 = banana", and so on:
      
      ['apple', 'banana', 'lemon'].each(function(item, index){
          alert(index + " = " + item);
      }); 
      
      //The optional second argument for binding isn't used here.
      

      因此,代码中的this对应于MooTools类,因此调用this.setSettings()将调用Class的方法setSettings,这是代码的最后一行你发布了。

答案 1 :(得分:-1)

Jquery中的

.each()函数类似于foreach函数。如果你没有初始化.each()函数的参数,那么它将整个元素作为对象返回。

例如,如果我们像

那样引用,网页上有div元素的div元素
$(".Div").each(function(){ return this; })

它将整个元素作为对象返回,如{div1,div2,....}

如果你需要将它作为单个元素返回,你必须为每个函数的参数设置索引和元素,如

$(".Div").each(function(index, element){ 
return this; // this returns only one element until the object ends. 
});