Javascript库中每个循环元素

Javascript library each looping elements

本文关键字:循环 元素 Javascript      更新时间:2023-09-26

我有问题。我有自己的类似jquery的库。我调用$或Meh(这就是它的名字——Mehlib),并作为参数传递选择器。这个库调用document.querySelectorAll,返回一个nodeList。要处理这个列表中的元素(节点)(我的意思是,为它们调用一个方法),我必须循环它们。我已经这样想了:

$('.selector-class').each(function (el) {
    el.style.display = 'none'; // hide element
});
Meh.fn = Meh.prototype = {
    map: function (callback) {
        var match = [];
        for (var i = 0; i < this.length; i++) {
            push.call( match, callback.call( this, this[i], i ) );
        }
        return match;
    },
    each: function (callback) {
        return this.map(callback);
    }
};

所以,这很好,但让我们认为自己懒惰,好吗?当循环(映射)到this时,我想"保存"一个当前元素并返回它

$('.selector-class').each(function () {
    this.style.display = 'none';
});

因此,我仍然想在映射节点时调用回调函数,但我不想将单个映射元素保存到回调的函数参数

我尝试在map方法中创建库的新实例,并将映射的重复单个节点保存到当前方法中,如this = duplicated[i];,但有一个未捕获的错误:Uncaught reference error: Invalid left-hand side in assignmentUncaught reference error: $ is not defined也有错误。

您不分配给this

但是,您可以在调用函数的上下文中定义什么是this

即:

someObject.someMethod(); // "this" is someObject
someFunction(); // "this" is typically "window" but may be "null"
someFunction.call(someThing, arg1, arg2); // "this" is someThing

在最后一个例子中,您将在调用函数时提供您想要的this

更改:

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

收件人:

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

因此,您将元素作为thisArg传入。