了解$ .proxy如何在内部工作

时间:2015-12-13 15:36:05

标签: javascript jquery

刚刚浏览了jQuery $ .proxy的源代码,并遇到了以下几行代码,见下文:

if (typeof context === "string") {
        tmp = fn[context];
        context = fn;
        fn = tmp;
    }

可以看到整个功能代码 HERE ,我想知道的是,上面的代码规定是什么,I.E。以上代码何时发挥作用?谁能解释一下?我完全理解代码正在做什么但是,我想知道的是一个真正的代码情况,其中这样的代码将是有用的。

EDIT ::

整个功能代码如下所示:

function (fn, context) {
    var args, proxy, tmp;

    if (typeof context === "string") {
        tmp = fn[context];
        context = fn;
        fn = tmp;
    }

    // Quick check to determine if target is callable, in the spec
    // this throws a TypeError, but we will just return undefined.
    if (!jQuery.isFunction(fn)) {
        return undefined;
    }

    // Simulated bind
    args = slice.call(arguments, 2);
    proxy = function () {
        return fn.apply(context || this, args.concat(slice.call(arguments)));
    };

    // Set the guid of unique handler to the same of original handler, so it can be removed
    proxy.guid = fn.guid = fn.guid || jQuery.guid++;

    return proxy;
}

谢谢。

1 个答案:

答案 0 :(得分:2)

您似乎理解$.proxy的目的,但想知道何时能够将字符串作为“上下文”传递是有用的?好吧,我看待它的方式主要是偏好问题,因为两个签名都可以互换使用。

以下是$ .proxy(或Funtion.prototype.bind)的典型用法:

var user = {
    username: 'Thomas Mann',
    getUsername: function() {
        alert(this.username);
    }
};

$('button').click($.proxy(user.getUsername, user));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button>Check</button>

没什么特别的。但是,jQuery代理实现允许您交换基础对象和上下文,因此上面的示例也可以重写如下:

var user = {
    username: 'Thomas Mann',
    getUsername: function() {
        alert(this.username);
    }
};

$('button').click($.proxy(user, 'getUsername'));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button>Check</button>

因此,在这种情况下,首先传递上下文,然后传递方法名称以调用上下文对象。

但请注意,经典Function.prototype.bind遵循第一种表示法。我建议做同样的事情以保持一致性。我还没有看到有人使用它的第二种方式,以便更好地避免这种不太清晰的语法。

相关问题