向过去学习的 JavaScript - 绑定方法的实现
最编程
2024-05-01 08:55:06
...
bind()
方法和apply()
、call()
相似,都可以用来改变某个函数运行时this
的指向。
并且同样接受的第一个参数作为它运行时的this
,之后的参数都会传入作为它的参数。
但是bind()
还有一个最大的特点就是它会创建一个新的函数,以便于我们稍后作调用,这也是它区别于apply()
和call()
的地方。
先来看下bind
的使用
var foo = {
value: 1
};
function bar() {
return this.value;
}
var bindFoo = bar.bind(foo);
console.log(bindFoo()); // 1
模拟实现一
Function.prototype.bind2 = function(context) {
// 将this作保存,代表被绑定的函数
var self = this;
return function() {
// 绑定函数可能会有返回值,所以这里要return一下
return self.apply(context);
}
}
bind的传参:需要注意我们在bind的时候可以进行传参,并且在执行bind返回的函数的时候依然可以传参。如下例子:
var foo = {
value: 1
};
function bar(name, age) {
console.log(this.value);
console.log(name);
console.log(age);
}
var bindFoo = bar.bind(foo, 'xiao');
bindFoo('18');
// 1
// xiao
// 18
传参效果的实现
Function.prototype.bind2 = function (context) {
var self = this;
// 获取 bind2 函数从第二个参数到最后一个参数
var args = Array.prototype.slice.call(arguments, 1);
return function () {
// 这里的arguments是指bind返回的函数传入的参数
var bindArgs = Array.prototype.slice.call(arguments);
return self.apply(context, args.concat(bindArgs));
}
}
bind还有一个特点:就是 bind 返回的函数可以被作为构造函数来使用,此时 bind 指定的this值会失效,但传入的参数依然生效。如下例子:
var value = 2;
var foo = {
value: 1
};
function bar(name, age) {
this.habit = 'shopping';
console.log(this.value);
console.log(name);
console.log(age);
}
bar.prototype.friend = 'kevin';
var bindFoo = bar.bind(foo, 'daisy');
var obj = new bindFoo('18');
// undefined
// daisy
// 18
console.log(obj.habit);
console.log(obj.friend);
// shopping
// kevin
可以看到由于这里使用了new
操作符,this
已经指向了obj
,因此this.value
打印出来为undefined
。
构造函数效果的实现
为了让this
指向new
出来的对象,我们可以通过修改返回的函数的原型来实现
Function.prototype.bind2 = function (context) {
var self = this;
var args = Array.prototype.slice.call(arguments, 1);
var fBound = function () {
var bindArgs = Array.prototype.slice.call(arguments);
// 判断是否作用构造函数
// 当作为构造函数时,将绑定函数的 this 指向 new 创建的实例,可以让实例获得来自绑定函数的值
// 当作为普通函数时,将绑定函数的 this 指向 context
return self.apply(this instanceof fBound ? this : context, args.concat(bindArgs));
}
// 修改返回函数的 prototype 为绑定函数的 prototype,实例就可以继承绑定函数的原型中的值
fBound.prototype = this.prototype;
return fBound;
}
不过上面的写法还存在点问题,fBound.prototype = this.prototype
这一句代码直接修改了 fBound.prototype
,也会直接修改绑定函数的 prototype。如下例子:
function bar() {}
var bindFoo = bar.bind2(null);
// 修改 bindFoo 的值
bindFoo.prototype.value = 1;
// 导致 bar.prototype 的值也被修改了
console.log(bar.prototype.value) // 1
因此可以通过一个空函数作一个中转,避免绑定函数的 prototype 的属性被修改:
Function.prototype.bind2 = function (context) {
var self = this;
var args = Array.prototype.slice.call(arguments, 1);
var fNOP = function () {};
var fBound = function () {
var bindArgs = Array.prototype.slice.call(arguments);
return self.apply(this instanceof fNOP ? this : context, args.concat(bindArgs));
}
fNOP.prototype = this.prototype;
fBound.prototype = new fNOP();
return fBound;
}
当调用bind的不是函数还得做一下错误处理,完整实现如下:
Function.prototype.bind2 = function (context) {
if (typeof this !== "function") {
throw new Error("Function.prototype.bind - what is trying to be bound is not callable");
}
var self = this;
var args = Array.prototype.slice.call(arguments, 1);
var fNOP = function () {};
var fBound = function () {
var bindArgs = Array.prototype.slice.call(arguments);
return self.apply(this instanceof fNOP ? this : context, args.concat(bindArgs));
}
fNOP.prototype = this.prototype;
fBound.prototype = new fNOP();
return fBound;
}
结尾
对于这篇文章理解起来有难度的话,建议先回顾一下原型,作用域和闭包相关的知识,可以看看我之前的文章,这些知识点都是相互关联的。链接在下方:
系列文章:
- JavaScript温故而知新——原型和原型链
- JavaScript温故而知新——执行环境和作用域
- JavaScript温故而知新——作用域链和闭包
- JavaScript温故而知新——函数的4种调用方式
- JavaScript温故而知新——call()和apply()的实现
推荐阅读
-
向过去学习的 JavaScript - 绑定方法的实现
-
JavaScript 向过去学习--执行上下文和执行堆栈的机制
-
javascript 基础教程 [向过去的教程学习]
-
向过去学习:新方法和覆盖方法的区别以及虚拟方法和抽象方法的区别
-
向过去学习生成器的设计模式
-
JavaScript 实现数字在前面补 "0 "的五种方法示例
-
推荐系统与深度学习的结合--linUCB 方法的分析与实现
-
JavaScript 实现单词首字母大写的方法总汇
-
JavaScript 实现斐波那契数列的四种方法介绍(代码)
-
[姿势估计] 实践记录:使用 Dlib 和 mediapipe 进行人脸姿势估计 - 本文重点介绍方法 2):方法 1:基于深度学习的方法:。 基于深度学习的方法:基于深度学习的方法利用深度学习模型,如卷积神经网络(CNN)或递归神经网络(RNN),直接从人脸图像中学习姿势估计。这些方法能够学习更复杂的特征表征,并在大规模数据集上取得优异的性能。方法二:基于二维校准信息估计三维姿态信息(计算机视觉 PnP 问题)。 特征点定位:人脸姿态估计的第一步是通过特征点定位来检测和定位人脸的关键点,如眼睛、鼻子和嘴巴。这些关键点提供了人脸的局部结构信息,可用于后续的姿势估计。 旋转表示:常见的旋转表示方法包括欧拉角和旋转矩阵。欧拉角通过三个旋转角度(通常是俯仰、偏航和滚动)描述头部的旋转姿态。旋转矩阵是一个 3x3 矩阵,表示头部从一个坐标系到另一个坐标系的变换。 三维模型重建:根据特征点的定位结果,三维人脸模型可用于姿势估计。通过将人脸的二维图像映射到三维模型上,可以估算出人脸的旋转和平移信息。这就需要建立人脸的三维模型,然后通过优化方法将模型与特征点对齐,从而获得姿势估计结果。 特征点定位 特征点定位是用于检测人脸关键部位的五官基础部分,还有其他更多的特征点表示方法,大家可以参考我上一篇文章中介绍的特征点检测方案实践:人脸校正二次定位操作来解决人脸校正的问题,客户在检测关键点的代码上略有修改,坐标转换部分客户见上图 def get_face_info(image). img_copy = image.copy image.flags.writeable = False image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB) results = face_detection.process(image) # 在图像上绘制人脸检测注释。 image.flags.writeable = True image = cv2.cvtColor(image, cv2.COLOR_RGB2BGR) box_info, facial = None, None if results.detections: for detection in results. for detection in results.detections: mp_drawing.Drawing.detection = 无 mp_drawing.draw_detection(image, detection) 面部 = detection.location_data.relative_keypoints 返回面部 在上述代码中,返回的数据是五官(6 个关键点的坐标),这是用 mediapipe 库实现的,下面我们可以尝试用另一个库:dlib 来实现。 使用 dlib 使用 Dlib 库在 Python 中实现人脸关键点检测的步骤如下: 确保已安装 Dlib 库,可使用以下命令: pip install dlib 导入必要的库: 加载 Dlib 的人脸检测器和关键点检测器模型: 读取图像并将其灰度化: 使用人脸检测器检测图像中的人脸: 对检测到的人脸进行遍历,并使用关键点检测器检测人脸关键点: 显示绘制了关键点的图像: 以下代码将参数 landmarks_part 添加到要返回的关键点坐标中。