.bind的替代品

时间:2014-08-04 13:27:04

标签: javascript jquery

我收到错误

typerror undefined is not a function

使用以下代码

var btnLeft = document.querySelector('' + this.config.el + ' .btn-carousel-sim-left');
btnLeft.addEventListener('click', this.snippet.carousel.previous.bind(this), false); // ERROR HERE

我认为.bind功能在目标浏览器上不可用。

我想知道另一种绑定解决方案(注意:我也可以使用jquery 1.9.1)。

2 个答案:

答案 0 :(得分:1)

我是使用bind的忠实粉丝,它让我的生活变得更轻松。

我使用本页底部的polyfill来确保绑定在所有浏览器中都有效:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind

希望有所帮助 - 如果您不确定如何使用填充物,请添加注释。

答案 1 :(得分:0)

我找到了一个使用以下脚本的解决方案,信用 JavaScript:The Definitive Guide,第6版

例8-5。 ECMAScript 3的Function.bind()方法

if (!Function.prototype.bind) {
    Function.prototype.bind = function(o /*, args */ ) { // Save the this and arguments values into variables so we can        // use them in the nested function below.       
        var self = this,
            boundArgs = arguments;
        // The return value of the bind() method is a function        
        return function() { // Build up an argument list, starting with any args passed          
            // to bind after the first one, and follow those with all args         
            // passed to this function.          
            var args = [],
                i;
            for (i = 1; i < boundArgs.length; i++) args.push(boundArgs[i]);
            for (i = 0; i < arguments.length; i++) args.push(arguments[i]);
            // Now invoke self as a method of o, with those arguments           
            return self.apply(o, args);
        };
    };
}
相关问题