在EventListeners上使用function.prototype.bind() [英] Usage of function.prototype.bind() on EventListeners

查看:115
本文介绍了在EventListeners上使用function.prototype.bind()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我看过这段代码:

Function.prototype.bind = function (bind) {
    var self = this;
    return function () {
        var args = Array.prototype.slice.call(arguments);
        return self.apply(bind || null, args);
    };
};

在javascript的某些实现中,用于处理EventListener

in some implementation on javascript and used for handle EventListener

element.addEventListener('mousedown', this.mykeydownhandler.bind(this), false);

可以解释我这个功能

推荐答案

这只是标准的一个自制实现 Function.bind 功能:

That's just a homebrew implementation of the standard Function.bind function:


创建一个新的函数,当被调用时,它自己在提供的这个值的上下文中调用这个函数,当调用新函数时,给出一个给定的参数序列

Creates a new function that, when called, itself calls this function in the context of the provided this value, with a given sequence of arguments preceding any provided when the new function was called.

应该用一些排序功能检测来包装,以便它只能用于具有后面JavaScript引擎的浏览器

That should be wrapped with some sort feature detection so that it only gets used for browsers with a behind-the-times JavaScript engine.

只是说这个问题:

element.addEventListener('mousedown', this.mykeydownhandler, false);

this.mykeydownhandler 是一个未绑定函数,该函数内的这个的值将在调用时确定。所以,如果 mykeydownhandler 取决于什么这个,那么当触发事件时,你不会有正确的上下文。当你这样说:

Is that this.mykeydownhandler is an unbound function and the value of this inside that function will be determined when it is called. So, if mykeydownhandler depends on what this is then you won't have the right context when the event is triggered. When you say this:

element.addEventListener('mousedown', this.mykeydownhandler.bind(this), false);

使用本机 bind 或homebrew在你的问题的替换,这个 addEventListener 调用的将与相同里面 mykeydownhandler

using either the native bind or the homebrew replacement in your question, the this in the addEventListener call will be the same as this inside mykeydownhandler.

这篇关于在EventListeners上使用function.prototype.bind()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆