bind的模拟和实现

minute_5

关注

阅读 36

2022-03-14

bind函数的作用

改变this指向,返回一个新的函数

参数的相关情况

若第一个参数为null,则this指向window;
若参数有值,则this指向该参数;
若新函数被当作构造函数使用时,则第一个参数无效

Function.prototype.myBind = function(target) {
	target = target || window
	let self = this
	let args = [].slice.call(arguments, 1)
	const F = function(){}
	const fn = function() {
		let _arg = [].slice.call(arguments, 0)
		return self.apply(this instanceof F ? this : target, args.concat(_arg))
	}
	F.prototype = this.prototype
	fn.prototype = new F()
	return F
}

精彩评论(0)

0 0 举报