手写bind,apply,call和new
# 手写 bind,apply,call 和 new
# 实现 bind
Function.prototype.MyBind = function() {
var _this = this
var context = arguments.shift()
var args = Array.prototype.slice.call(arguments)
return function Fn() {
var _args = [].concat(args, Array.prototype.slice.call(arguments))
return _this.apply(context, _args)
}
}
1
2
3
4
5
6
7
8
9
2
3
4
5
6
7
8
9
# 实现 apply
Function.prototype.MyApply = function() {
var fn = arguments.shift()
var args = Array.prototype.slice.call(arguments[0])
fn.__this = this
var result = fn.__this(...args)
delete fn.__this
return result
}
1
2
3
4
5
6
7
8
9
2
3
4
5
6
7
8
9
# 实现 call
Function.prototype.MyCall = function() {
var fn = arguments.shift()
var args = Array.prototype.slice.call(arguments)
fn.__this = this
var result = fn.__this(...args)
delete fn.__this
return result
}
1
2
3
4
5
6
7
8
9
2
3
4
5
6
7
8
9
# 实现 new
function MyNew (Fn, ...args) {
var obj = Object.create(Fn.prototype)
let result = Fn.apply(obj, args)
return typeof result === 'object' ? result : obj
}
1
2
3
4
5
2
3
4
5
上次更新: 2021/09/13, 15:11:59