【问题标题】:How to use bind without losing `this` reference?如何在不丢失“this”引用的情况下使用绑定?
【发布时间】:2019-09-03 18:00:35
【问题描述】:

有没有办法在不丢失事件处理程序提供的this 绑定的情况下将附加参数部分应用于函数。 bind 需要 this 值,因此将 null 作为第一个参数会丢失对 DOM 元素 <button>Click</button> 的引用,否则会出现该引用。最好提供像 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 作为绑定的第一个参数即可达到效果,但我感兴趣的是不要“丢失”绑定的this,而不是将其替换为对元素的引用.

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

【问题讨论】:

  • 传递this 作为第一个参数?真的不清楚你在问什么。
  • 那里 必须 成为这个的欺骗目标,但我没有立即找到它。基本上,你必须写一个“咖喱”函数:function curry(fn, ...args1) { return function(...args2) { return fn.call(this, ...args1, ...args2); }; }
  • 另外,.bind()=> 函数没有任何作用,是吗?
  • @Pointy 你是对的。我在写示例时错过了这一点。
  • 请注意,您仍然可以使用event.currentTarget访问该元素

标签: javascript dom events dom-events


【解决方案1】:

必须成为这个的欺骗目标。基本上,你必须写一个“咖喱”函数:

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

【讨论】:

  • 为什么需要returnfn.call
  • @1252748 - fn.call 调用 fnthis 设置为 call 的第一个参数,并在其第二个参数中提供参数。我返回它提供的结果,这样如果原始函数有返回值,它就会被柯里化函数返回。
  • 谢谢。我重新发布了该评论以明确我是在专门询问return,但看起来我是在您发布答案后才提交的。这就回答了。干杯。
  • “这里必须成为这个的欺骗目标”。 > “dupetarget”是什么意思?
  • @1252748 - 俚语。 dupetarget 是一个已经被询问和回答的问题,可以用作“关闭为重复”投票的目标。我认为必须有一个,但我找不到它,我注意到从那以后就没有人了,所以...... :-)
猜你喜欢
  • 2012-11-30
  • 1970-01-01
  • 2012-03-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-12-31
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多