手写bind函数
面试经常问到,能不能实现一个bind函数
当时立马写了一个无脑的bind
function bind(fn, obj, ...arr) {
return fn.apply(obj, arr)
}
但是这种bind函数,一看就问题重重
函数柯里化怎么用?
new 情况怎么办?
原型对象有考虑嘛?
要是写出上面的bind函数,那么你的面试可能也会因此“草草结束”
所以下面就跟着我,五层速记bind函数原理,并实现一个自己的bind
让面试官对你刮目相看
第一层 - 绑定在原型上的方法
这一层非常的简单,因为JS原型链的特性,当我们在函数的原型对象上挂载了一个方法时,
通过xxx.bind的时候,调用的是函数原型上的方法
Function.prototype.myBind = function(){}
function add(){}
add.myBind // 调用的就是原型上的myBind方法
详情请看下图:
第二层 - 改变this的指向
这可以说是 bind 最核心的特性了,就是改变 this 的指向,并且返回一个函数。而改变 this , 我们可以通过已知的 apply 和 call 来实现,这里我们就暂且使用 apply 来进行模拟。首先通过 self
来保存当前 this,也就是传入的函数。因为我们知道 this 具有 隐式绑定
的规则(摘自 《你不知道的JavaScript(上)》2.2.2 )
代码实现:
Function.prototype.myBind = function (thisObj) {
const fn = this
return function () {
fn.apply(thisObj)
}
}
下面让我们看看测试:
let obj = { a: 1 }
function myname() { console.log(this.a) }
myname.myBind(obj)(); // 1
可能很多朋友都止步于此了,因为在一般的面试中,特别是一些校招面试中,可能你只需要知道前面两个就差不多了。但是想要在面试中惊艳所有人,仍然是不够的,接下来我们继续我们的探索与研究。
第三层 - 支持柯里化
函数柯里化,是一个老生常谈的话题了,这里就不再赘述了,不了解的可以去我之前分享的函数柯里化的文章中看
而我们的 bind 函数也是类似,我们通过获取当前外部函数的 arguments
,保存成变量 args
,最后 return
的方法,再一次获取当前函数的 arguments
, 最终用 finalArgs
进行了一次合并。
Function.prototype.myBind = function (thisObj, ...args) {
const fn = this
return function () {
const finalArgs = [...args, ...arguments]
fn.apply(thisObj, finalArgs)
}
}
下面看看代码实现效果:
let obj = { i: 1 }
function myFun(a, b, c) {
console.log(this.i + a + b + c);
}
let myFun1 = myFun.myBind(obj, 1, 2);
myFun1(3); // 7
一般到了这层,可以说非常棒了,但是再坚持一下下,就变成了完美的答卷。
第四层 - 考虑 new 的调用
要知道,我们的方法,通过 bind 绑定之后,依然是可以通过 new 来进行实例化的, new
的优先级会高于 bind
(摘自 《你不知道的JavaScript(上)》2.3 优先级)。
这一点我们通过原生 bind 和我们第四层的 _bind 来进行验证对比。
// 原生
var obj = { i: 1}
function myFun(a, b, c) {
// 此处用new方法,this指向的是当前函数 myFun
console.log(this.i + a + b + c);
}
var myFun1 = myFun.bind(obj, 1, 2);
new myFun1(3); // NAN
// 第四层的 bind
var obj = { i: 1}
function myFun(a, b, c) {
console.log(this.i + a + b + c);
}
var myFun1 = myFun._bind(obj, 1, 2);
new myFun1(3); // 7
注意,这里第一个函数使用的是 bind
方法
因此我们需要在 bind 内部,对 new 的进行处理。而 new.target
属性,正好是用来检测构造方法是否是通过 new
运算符来被调用的。
接下来我们还需要自己实现一个 new ,
而根据
MDN
,new
关键字会进行如下的操作:1.创建一个空的简单JavaScript对象(即
{}
);2.链接该对象(设置该对象的constructor)到另一个对象 ;
3.将步骤1新创建的对象作为
this
的上下文 ;4.如果该函数没有返回对象,则返回
this
。
看下实现的代码:
Function.prototype.myBind = function (thisObj, ...args) {
const fn = this
return function () {
const finalArgs = [...args, ...arguments]
// 判断是否有调用new关键字
if(new.target !== undefined){
// 构造函数的返回值,注意这里的this为实例对象
const result = fn.apply(this, finalArgs)
if(result instanceof Object){
//如果返回的是对象类型的值则返回该对象
return result
}else{
// 如果返回的是正常的值类型
// 则返回该实例对象
return this
}
}else{
// 如果没有new调用则按原来的操作
fn.apply(thisObj, finalArgs)
}
}
}
看下测试的代码:
let obj = {name:'zss',age:18}
function say(name,age){
this.name=name
this.age=age
console.log(this); // new 的优先级要高于bind,故this为该实例对象
console.log(this.name); // 孙悟空
}
const xxx = say.myBind(obj)
// new 的优先级要高于bind,故this为该实例对象
console.log(new xxx('孙悟空',29)); // 输出 {name: "孙悟空", age: 29}
看到这里,你的造诣已经如火纯情了,但是最后还有一个小细节。
第五层 - 保留函数原型
以上的方法在大部分的场景下都没有什么问题了,但是,当我们的构造函数有 prototype 属性的时候,就出问题啦。因此我们需要给 prototype 补上,还有就是调用对象必须为函数。
Function.prototype.myBind = function (thisObj, ...args) {
// 规定调用bind的必须是函数
if(typeof this !== 'function' || {}.toString.call(this) !== '[object Function]'){
throw new Error(`${this} must be a function`)
}
const fn = this
let bound = function () {
const finalArgs = [...args, ...arguments]
// 判断是否有调用new关键字
if(new.target !== undefined){
// 构造函数的返回值,注意这里的this为实例对象
const result = fn.apply(this, finalArgs)
if(result instanceof Object){
//如果返回的是对象类型的值则返回该对象
return result
}else{
// 如果返回的是正常的值类型
// 则返回该实例对象
return this
}
}else{
// 如果没有new调用则按原来的操作
return fn.apply(thisObj, finalArgs)
}
}
//继承函数的原型
if(fn.prototype){
// 为什么使用了 Object.create? 因为我们要防止,bound.prototype 的修改而导致self.prototype 被修改。
// 不要写成 bound.prototype = self.prototype; 这样可能会导致原函数的原型被修改。
bound.prototype = Object.create(fn.prototype)
bound.prototype.constructor = fn
}
return bound
}
以上就是一个比较完整的 bind 实现了,如果你想了解更多细节的实践,可以查看。(也是 MDN 推荐的)
https://github.com/Raynos/function-bind
总结最终版bind函数
Function.prototype.myBind = function (thisObj, ...args) {
// 规定调用bind的必须是函数
if(typeof this !== 'function' || {}.toString.call(this) !== '[object Function]'){
throw new Error(`${this} must be a function`)
}
const fn = this
let bound = function () {
const finalArgs = [...args, ...arguments]
// 判断是否有调用new关键字
if(new.target !== undefined){
// 构造函数的返回值,注意这里的this为实例对象
const result = fn.apply(this, finalArgs)
if(result instanceof Object){
//如果返回的是对象类型的值则返回该对象
return result
}else{
// 如果返回的是正常的值类型
// 则返回该实例对象
return this
}
}else{
// 如果没有new调用则按原来的操作
return fn.apply(thisObj, finalArgs)
}
}
//继承函数的原型
if(fn.prototype){
// 为什么使用了 Object.create? 因为我们要防止,bound.prototype 的修改而导致self.prototype 被修改。
// 不要写成 bound.prototype = self.prototype; 这样可能会导致原函数的原型被修改。
bound.prototype = Object.create(fn.prototype)
bound.prototype.constructor = fn
}
return bound
}
看下测试代码:
let test1 = {age:18}
function say(a,b,c){
return a+b+c+this.age
}
const xxx = say.myBind(test1)
console.log(xxx(1,2,3)); // 24
function Person(name,age){
this.name = name
this.age = age
}
Person.prototype.say = function say(){
console.log(this.name,this.age);
}
let obj = {name:'孙悟空',age:18}
const inherit = Person.myBind(obj)
const test2 = new inherit('白骨精',28)
test2.say() // '白骨精',28
// 原因new的优先级高于bind,所以this为new的实例对象
最好一步一步的跟着敲然后理解,最后你也能实现一个让面试官满意的bind函数!