手写bind call apply函数
程序员文章站
2022-03-08 09:43:33
...
apply
Function.prototype.myApply = function (thisArg, ArgArray) {
if (typeof thisArg == 'undefined' || typeof thisArg == null) {
thisArg = window
}
let fnSymbol = Symbol()
thisArg[fnSymbol] = this
let ret = thisArg[fnSymbol](...ArgArray)
delete thisArg[fnSymbol]
return ret
}
function say(age) {
console.log(`我的名字是${this.name},年龄${age}啦`)
}
say.myApply({ name: 'zhq' }, [18])
call
Function.prototype.myCall = function (thisArg, ...ArgArray) {
if (typeof thisArg === 'undefined' || typeof thisArg === null) {
thisArg = window
}
let fnSymbol = Symbol()
thisArg[fnSymbol] = this
let ret = thisArg[fnSymbol](...ArgArray)
delete thisArg[fnSymbol]
return ret
}
function say(age) {
console.log(`我的名字是${this.name},年龄${age}啦`)
}
say.myApply({ name: 'zhq' }, [18])
bind
Function.prototype.myBind = function (thisArg, ...ArgArray) {
let thatFunc = this
return function () {
thatFunc.apply(thisArg, ArgArray)
}
}
上面仅为实现,没有兼容性
Polyfill写法
if (!Function.prototype.bind){
;(function(){
let slice = Array.prototype.slice;
let thatArg = arguments[0];
let args = slice.call(arguments, 1);
Function.prototype.bind = function (thisArg, ...ArgArray) {
let thatFunc = this
return function () {
let funcArgs = args.concat(slice.call(arguments))
thatFunc.apply(thatArg, funcArgs)
}
}
})()
}
下一篇: Ubuntu创建新用户并增加管理员权限
推荐阅读
-
浅谈JavaScript中的apply/call/bind和this的使用
-
javascript中call apply 与 bind方法详解
-
js中的call bind apply简单分析
-
javascript中apply、call和bind的使用区别
-
【THE LAST TIME】this:call、apply、bind
-
Javascript函数内置方法call/apply实例讲解
-
javascript基于原型链的继承及call和apply函数用法分析
-
Javascript中apply、call、bind的用法讲解
-
浅谈JavaScript中的apply/call/bind和this的使用
-
JavaScript函数apply()和call()用法与异同分析