JavaScript Bind方法的区别

时间:2015-02-18 19:46:14

标签: javascript

之间有什么区别吗?
foo.bind(this)(arg1, arg2);

foo.bind(this, arg1, arg2)();

这两个代码在许多网站上运行正常,但在一个网站中,第二个示例因arg2undefined而导致错误。

更新更复杂的例子

// Create an immediately invoked functional expression to wrap our code
(function () {

    // Define our constructor 
    this.Widget = function (options) {

        this.widgetWrap = null;
        this.widgetHeaderTitle = null;

        //Code removed for clarity

        // Establish our default settings
        this.options = extend({
            formHeaders: ['Заголовок 1', 'Заголовок 2'],
        }, options);

        this.init();

    };

    // Public Methods

    Widget.prototype.init = function () {

        //Code removed for clarity

        contentAnimation.bind(this)(this.widgetHeaderTitle, this.options.formHeaders);

        //Not working on http://healthyclinic.ru/ but working on any other site
        //this.options.formHeaders - Array with several elements. NOT NULL and NOT UNDEFINED
        //contentAnimation.bind(this, this.widgetHeaderTitle, this.options.formHeaders)();

        //Code removed for clarity

    };

    // Private Methods

    function contentAnimation(el, arr) {
        //In this place with second example 'arr' already UNDEFINED
        var self = this;
        var current = 1;
        self.titleAnimationInterval = setInterval(function () {
            el.style.opacity = 0;
            setTimeout(function () {
                el.textContent = arr[current];
                el.style.opacity = 1;
                current = ++current % arr.length;
            }, self.options.transitionDuration);
        }, 4000);
    }

    //Code removed for clarity

}());

在上面的代码中,您可以看到我的库中的代码。代码在许多站点和本地机器上都能正常工作,只有一个站点的第二个参数变为undefined

1 个答案:

答案 0 :(得分:0)

不,假设foo是一个函数而foothe built-in function method,两者之间的功能没有区别(.bind()能够检测到)