javascript - 这是一个好的绑定(bind)方法吗?

标签 javascript

Function.prototype.bind = function() {
    var $this = arguments[0];
    return this.apply($this, Array.prototype.slice.call(arguments, 1));
};

在实际应用中是否足够好?

最佳答案

没有。这段代码有一些我不喜欢的地方,以及它不起作用的一些原因。

首先,大多数人不会以这种方式分配参数。它占用额外的空间而没有额外的效果。如果变量名称应根据参数数量/参数类型更改,则仅使用 arguments 变量。要分配 $this 你应该这样做..

Function.prototype.bind = function($this) {

其次,bind 应该返回一个函数。您的返回任何 this 返回的内容。您的函数更像是 Function:call,然后是 Function:bind

要修复它,您需要做的是让它返回一个函数,该函数在运行时将返回函数返回的任何内容。

试试这个:

Function.prototype.bind = function($this) {
    // `this` changes inside the function, so we have to give it a safe name.
    var self = this;
    return function () {
        return self.apply($this, Array.prototype.slice.call(arguments, 1));
    }
};

此外,更多现代浏览器内置了此函数的 ECMAScript 5 标准。该函数是用纯 JavaScript 编写的,因此对于较旧的浏览器,只需包含此 code suggested by Mozilla :

if ( !Function.prototype.bind ) {
    Function.prototype.bind = function( obj ) {
        var slice = [].slice,
            args = slice.call(arguments, 1),
            self = this,
            nop = function () {},
            bound = function () {
                return self.apply( this instanceof nop ? this : ( obj || {} ), args.concat( slice.call(arguments) ) );
            };
        nop.prototype = self.prototype;
        bound.prototype = new nop();
        return bound;
    };
}

关于javascript - 这是一个好的绑定(bind)方法吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6142528/

相关文章:

javascript - 通过索引删除数组对象

javascript - 用于任一/或单选按钮的 jQuery 表单验证

JavaScript - 解构对象中的默认值作为参数传递给箭头函数

javascript - CSS3 或 Jquery : popup of a thumbnail image when the thumbnail is hovered over

javascript - 加速器钛 : Creating a new file

javascript - jQuery 在 1 个元素中打开元素

javascript - Angularjs 使用电子邮件类型重置表单字段

javascript - 是否可以使用 snap.svg 加载 svg 文件的一部分?

Javascript高度和媒体查询同时进行

javascript - 加载后移除 Cufon