如何将所选元素传递给'这'在链接函数中

How to pass selected element to 'this' in the chained functions

本文关键字:链接 函数 元素      更新时间:2023-10-09

我正在努力了解链式函数是如何工作的,特别是如何将所选元素传递给链式函数。

假设我们有一个链式函数如下:

var func = {};
func.remove= function() {
    $(this).remove();
}

如何通过jQuery或JavaScript选择元素并将其传递给链接函数,如下所示:

var elm = $("foo");
elm.func.remove();

var elm2 = document.getElementById("foo");
elm2.func.remove();

链式函数是一种返回被调用对象的方法(因此,除非扩展本机DOM对象,否则它不能返回元素本身,这是不推荐的)。

func没有被链接,因为它根本不是一个函数。remove在不返回其所属对象之前不会被链接。

如果要执行与元素一起工作的链式函数,则需要定义一个对象,在该对象上定义链式方法,并将元素存储为该对象的属性。

例如:

function MyConstructor(element) {
    this._element = element;
}
MyConstructor.prototype.doA = function doA () {
    console.log(this._element);
    return this;
};
MyConstructor.prototype.doB = function doB () {
    element.style.display = "none";
    return this;
};
var example = new MyConstructor(document.getElementById('foo'));
example.doA().doB();