1. call函数实现
Function.prototype.gfcall = function (thisArg, argArray) {
// 1. 获取需要被执行的函数 获取调用gfcall的函数对象
var fn = this
// 2. 对thisArg转换成对象类型(防止传入的是非对象类型,转换成对象类型后,可以识别转换传入的this指向的对象的对应类型(例如字符串,数字,数组等类型))
thisArg = (thisArg !== null && thisArg !== undefined) ? Object(thisArg) ? window
// 3. 调用需要被执行的函数
thisArg.fn = fn
var result = thisArg.fn(...args)
// 给传入的函数添加属性/方法后要删除
delete thisArg.fn
//4. 将最终函数的结果返回
return result
}
function foo() {
console.log("foo函数被执行", this)
}
function sum(num1, num2) {
console.log("sum函数被执行", this, num1, num2)
return num1 + num2
}
// 系统的函数的call方法
foo.call(undefined) // window
var result = sum.call({}, 20, 30)
console.log("系统调用的结果:", result) // Object {} 50
// 自己实现的函数的hycall方法
// 默认进行隐式绑定
// foo.gfcall({name: "why"})
foo.gfcall(undefined) // window
var result = sum.gfcall("abc", 20, 30)
console.log("gfcall的调用:", result) // String "abc" 50
2. apply函数实现(参数以数组形式传入)
要求传入的参数以数组形式传入
Function.prototype.gfapply = function (thisArg, argArray) {
// 1. 获取要执行的函数
var fn = this
// 2. 处理绑定的thisArg
thisArg = (thisArg !== null && thisArg !== undefined) ? Object(thisArg) : window
// 3. 执行函数
thisArg.fn = fn
var result
argArray = argArray ? argArray: []
result = this.fn(...argArray)
delete thisArg.fn
// 4. 返回结果
return result
}
function sum(num1, num2) {
console.log("sum被调用", this, num1, num2)
return num1 + num2
}
// 系统调用
var result = sum.apply("abc", [20, 30])
console.log(result) // String "abc" 50
// 自己实现调用
var result1 = sum.gfapply("abc", [20, 30])
console.log(result) // String "abc" 50
3. bind函数实现(返回新函数)
调用后会返回一个函数
Function.prototype.gfbind = function (thisArg, ...argArray) {
// 1. 获取要执行的函数
var fn = this
// 2. 对thisArg转换成对象类型(防止传入的是非对象类型,对象类型可以识别转换传入的this对象的对应类型)
thisArg = (thisArg !== null && thisArg !== undefined) ? Object(thisArg) ? window
function proxyFn(...args) {
// 3. 将函数放到thisArg中调用
thisArg.fn = fn
var finalArgs = [...argArray, ...args]
var result = thisArg.fn(finalArgs)
delete thisArg.fn
// 4. 返回结果
return result
}
return proxyFn
}
function foo() {
console.log("foo被执行", this)
return 20
}
function sum(num1, num2, num3, num4) {
console.log(num1, num2, num3, num4)
}
// 系统的bind使用
var bar = foo.bind("abc")
bar()
var newSum = sum.gfbind("abc", 10, 20)
var result = newSum(30, 40)
console.log(result) // String "abc" 10 20 30 40
这三种显示绑定this的函数,在js引擎中实现原理是j用c++编写的,想要了解实现原理,可以下载v8引擎源码进行查阅,本文章中只是做了个简单实现,可能还有很多边界情况没有考虑!