0
点赞
收藏
分享

微信扫一扫

bind的模拟和实现

minute_5 2022-03-14 阅读 36

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 条评论