javascript - 了解 $.proxy 内部如何工作

标签 javascript jquery

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

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

整个功能代码可见 HERE ,我想知道的是,上面的代码规定是什么,I.E.上面的代码什么时候开始起作用?谁能解释一下?我完全理解代码在做什么,但是,我想知道的是真实的代码情况,在这种情况下,这样一段代码会很有用。

编辑::

完整的功能代码如下:

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;
}

谢谢。

最佳答案

你似乎明白了 $.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遵循第一个符号。我建议为一致性做同样的事情。我也没有看到有人以第二种方式使用它,所以最好避免这种不太清晰的语法。

关于javascript - 了解 $.proxy 内部如何工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34252800/

相关文章:

javascript - 无法在html中显示json数据

javascript - 谁拥有创建标签的网站和标签中包含内容的网站之间的 iframe 标签?

javascript - 无法将更改事件绑定(bind)到 ajax 调用的文件输入

javascript - jQuery检查输入是否是类型复选框?

php - "Undefined property"尝试通过 php 将 javascript 表单数据保存到 mysql 数据库时

javascript - 在 Controller 之前从服务加载数据

jquery 点击不使用 css 'position :fixed' 属性

php - 将 slider 中的缩略图链接到主显示图像并正确弹出

javascript - 从编辑器(jQuery、ClEditor)外部将 html 添加到 WYSIWYG

javascript - 在左边移动一个 div,在一个 div 的右边移动另一个