0
点赞
收藏
分享

微信扫一扫

JavaScript 手写 Bind 函数

东林梁 2022-03-11 阅读 122

前言:

今天给大家带来手写 bind 函数,希望对大家有所帮助!

代码:

注意点:

  1. 需要返回一个函数
  2. 返回的函数 需要考虑 是不是 new
  3. 不是 new 需要 使用 apply 或者 call 指定 this
		Function.prototype.myBind = function(context){
			if (typeof this !== 'function') {
				throw new TypeError('Type Error !')
			}
			var _this = this;
			var args = [...arguments].slice(1);
			return function F(){
				if (this instanceof F) {
                    // 判断是不是 直接 new 此函数
					return new _this(...args,...arguments);
				}
				return _this.apply(context,args.concat(...arguments))
			}
		}

		var show = function(){
			console.log(this.name);
			console.log(...arguments);
		}

		let c = {
			name:'wjf'
		}
		show.myBind(c,1,2,3)(4,5,6)

        // wjf
        // 1 2 3 4 5 6
举报

相关推荐

0 条评论