gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 14:44:43 24 4
gpt4 key购买 nike

刚刚浏览了 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com