手写call,bind,apply

			//实现call
			var that = this ; //小程序环境
			function mySymbol(obj){
				let unique = (Math.random() + new Date().getTime()).toString(32).slice(0,8);
				if(obj.hasOwnProperty(unique)){
					return mySymbol(obj)
				}else {
					return unique;
				}
			}
			let Person = {
				name:'Tom',
				say(age = 23,city = '宁波',job = '前端'){
					console.log(`我叫${this.name},今年${age},在${city},从事${job}`)
				}
			}
			let Person1 = {
				name:'Tom1'
			}
			Function.prototype.MyCall = function(context){
				context =context || that; //小程序环境 PC环境为context =context || window;
				let fn = mySymbol(context);
				context.fn = this;
				let arg = [...arguments].slice(1);
				context.fn(...arg);
				delete context.fn;
			}
			Person.say.MyCall(Person1,23,'宁波','前端');
			Person.say.call(Person1,23,'宁波','前端');
			//实现apply
			
			Function.prototype.myApply = function(cxt,args){
				    cxt = cxt||that; //小程序环境为cxt = cxt||that; PC环境为cxt = cxt||window;
				    var fn = mySymbol(cxt);
				    cxt[fn] = this;
				    var result = cxt[fn](...args);
				    return result;
			}
			Person.say.myApply(Person1,['23','宁波','前端'])
			Person.say.apply(Person1,['23','宁波','前端'])
			
			Function.prototype.myBind = function(context){
				let self = this;
				let arg = [...arguments].slice(1);
				return function(){
					let newArg = [...arguments];
					return self.apply(context,arg.concat(newArg))
				}
			}
			
			let fn = Person.say.myBind(Person1,23);
			fn();
			fn('宁波','前端')

  记录学习

上一篇:HR 问“你目前有几个 Offer”,聪明人会怎么说?你呢!


下一篇:Java 方法