javascript - 试图理解绑定方法的底层代码
问题描述
我正在查看绑定实现的代码片段,并且正在努力理解它是如何工作的:
// Credit to Douglas Crockford for this bind method
if (!Function.prototype.bind) {
Function.prototype.bind = function (oThis) {
if (typeof this !== "function") {
// closest thing possible to the ECMAScript 5 internal IsCallable function
throw new TypeError ("Function.prototype.bind - what is trying to be bound is not callable");
}
var aArgs = Array.prototype.slice.call (arguments, 1),
fToBind = this,
fNOP = function () {
},
fBound = function () {
return fToBind.apply (this instanceof fNOP && oThis
? this
: oThis,
aArgs.concat (Array.prototype.slice.call (arguments)));
};
fNOP.prototype = this.prototype;
fBound.prototype = new fNOP ();
return fBound;
};
}
按顺序,我有以下问题:
我如何看待
this
in:if (typeof this !== "function")
?我的理解是,通常this
是指拥有/包含被调用函数的对象。在这种情况下,是那个对象:A)。函数原型?或 B)。包含应用绑定的函数的对象(即,如果我们有,someFunc.bind(someObj)
那么this
上面是否指的是持有的对象someFunc
?如果是,如果该对象包含除 之外的许多其他方法someFunc
怎么办?如果是这样,我们如何处理this
对象除了我们感兴趣的功能之外还包含许多无关功能的可能性,someFunc
?)var aArgs = Array.prototype.slice.call (arguments, 1)
. . . 为什么将1
作为参数传递给调用方法?在
fToBind = this
我有与上面#1相同的问题。具体指的 是什么?this
的目的是
(this instanceof fNOP && oThis)
什么?我(当然不正确)对此的解读是,“真实”的情况是何时this
是包含空函数且 oThis 不为 NULL 的对象的实例?如果是这种情况,为什么会导致this
,如果不是这种情况,为什么会导致 的“虚假”情况oThis
?中的连接发生了什么:
aArgs.concat (Array.prototype.slice.call (arguments))
?这里不会arguments
引用 fBound 的参数吗?如果是这样,为什么我们要将这些与bind
方法的参数连接起来(这是我假设aArgs
代表的)?服务于什么目的
fNOP.prototype = this.prototype; fBound.prototype = new fNOP ()
?毕竟,在下一行,函数返回fBound
. 返回是否fBound
意味着我们真的在返回fBound.prototype
(即fNOP()
is的一个新实例this.prototype
)?如果是这样,那不会忽略/“覆盖”:fBound = function() { return fToBind.apply (this instanceof fNOP && oThis ? this : oThis, aArgs.concat (Array.prototype.slice.call (arguments))); }
但如果不是,那么
fBound.prototype = new fNOP ()
分配的目的是什么?
解决方案
推荐阅读
- google-drive-api - 使用 API 密钥通过 REST 列出文件给出 403
- android - 如何在 Katalon Studio 中循环测试用例?
- web-applications - 如何从 Java 客户端应用程序获取 WebSphere 中应用程序的状态?
- javascript - 根据Vue.js中的特定项目值获取列表中的最后一个值
- group-by - Pyspark:如何计算单个 groupBy 中的 avg 和 count?
- r - d3 所有分支在彼此垂直树状图的顶部。r2d3 闪亮
- node.js - Sequelize:如何将字段定义为函数?
- javascript - Redux 字段中输入的首字母大写
- julia - 迭代 Julia 的动态多项式中的项
- python - Pycharm-无法安装opencv