0

this有没有办法在不丢失事件处理程序提供的绑定的情况下将附加参数部分应用于函数。bind需要一个值,因此将 null 作为第一个参数会丢失对否则会存在this的 DOM 元素的引用。在不丢失对元素的引用的情况下<button>Click</button>提供诸如allow之类的附加参数会很好bind

const button = document.querySelector('button')
function once(...args) {
  console.log(...args, this) // {prop: 'val'}, event, `Window`
  button.removeEventListener('click', bound)
}
const extraArgs = {
  prop: 'val'
}
const bound = once.bind(null, extraArgs)
button.addEventListener('click', bound)
<button>Click</button>

在这个例子中,可以通过button作为第一个参数传入 bind 来实现效果,但我感兴趣的是不要“丢失”绑定this,而不是用对元素的引用替换它。

如何在不丢失thisDOM 元素绑定的情况下向函数提供额外的参数?

4

1 回答 1

4

为此必须有一个欺骗目标。基本上,您必须编写一个“咖喱”函数:

function curry(fn, ...args1) {
    return function(...args2) {
        return fn.call(this, ...args1, ...args2);
    };
}

该函数创建并返回一个函数,该函数在被调用时调用原始传递的函数,并this提供 curried 参数,然后是提供给调用 curried 函数的参数。curried 函数返回调用原始函数的结果,以便调用者可以看到该结果。

现场示例:

function partial(fn, ...args1) {
    return function(...args2) {
        return fn.call(this, ...args1, ...args2);
    };
}

class Example {
    constructor(name) {
        this.name = name;
        this.withArgs = partial(this.method, 1);
    }
    method(a, b, c) {
        console.log(`this.name = ${this.name}, ${a}, ${b}, ${c}`);
    }
}

const e = new Example("example");
e.withArgs(2, 3); // this.name = example, 1, 2, 3

于 2019-09-03T18:07:26.397 回答