<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>手写bind函数</title>
</head>
<body>
<script>
function fn1(a, b, c){
console.log('this', this)
console.log(a, b, c)
return 'this is fn1'
}
// 手写bind
Function.prototype.mybind = function(){
// 将参数拆解为数组
const args = Array.prototype.slice.call(arguments)
// 获取this(数组的第一项)
const t = args.shift()
const self = this
// 返回一个函数
return function(){
return self.apply(t, args)
}
}
const fn2 = fn1.mybind({x:100}, 10, 20, 30)
const res = fn2()
console.log(res)
</script>
</body>
</html>
【面试题】手写bind函数
最新推荐文章于 2024-08-14 15:45:18 发布