题目
手写 bind 函数。
题解
1. 写用例
function fn1(a, b, c) {
console.log(a, b, c)
return 'this is fn1'
}
const fn2 = fn1.bind({x: 100}, 10, 20, 30); // 创建函数
const res = fn2(); // 函数调用
console.log(res) // 打印结果
2. 写入
Function.prototype.bind1 = function () {
}
Q:为什么把函数写入Functuon的原型里?
A:hasOwnProperty()
方法返回一个布尔值,表示对象自有属性(而不是继承来的属性)中是否具有指定的属性。此处为false,所以我们要写在原型链上。
3. 把参数拆解为数组
// 模拟 bind
Function.prototype.bind1 = function () {
// 将参数拆解为数组
const args = Array.prototype.slice.call(arguments)
}
Q:arguments是什么?
A:arguments
是一个对应于传递给函数的参数的类数组对象。
Q:Array.prototype.slice.call(arguments)是什么?
A:把参数转化成数组,arguments 是一个列表。
4. 挖掉this的第一项
// 模拟 bind
Function.prototype.bind1 = function () {
// 将参数拆解为数组
const args = Array.prototype.slice.call(arguments) // 把一个列表变成数组
// 获取 this(数组第一项)
const t = args.shift()
}
5. 保存this
// 模拟 bind
Function.prototype.bind1 = function () {
// 将参数拆解为数组
const args = Array.prototype.slice.call(arguments) // 把一个列表变成数组
// 获取 this(数组第一项)
const t = args.shift()
// fn1.bind(...) 中的 fn1
const self = this
}
6. 返回一个新函数
// 模拟 bind
Function.prototype.bind1 = function () {
// 将参数拆解为数组
const args = Array.prototype.slice.call(arguments) // 把一个列表变成数组
// 获取 this(数组第一项)
const t = args.shift()
// fn1.bind(...) 中的 fn1
const self = this
// 返回一个新函数
return function () {
return self.apply(t, args)
}
}