手动实现call, apply, bind

166 阅读1分钟
Function.prototype.myCall = function(ctx) {
	ctx = ctx || window;
	let args = [...arguments].slice(1);
	let fn = Symbol();
	ctx.fn = this;
	ctx.fn(...args);
	delete ctx.fn;
}

Function.prototype.myApply = function(ctx) {
	ctx = ctx || window;
	let fn = Symbol();
	ctx.fn = this;
	arguments[1] ? ctx.fn(...arguments[1]) : ctx.fn();
	delete ctx.fn;
}

Function.prototype.myBind = function(ctx){
	ctx = ctx || window;
	let args = [...arguments].slice(1);
	let that = this;
	return function() {
		let args1 = [...arguments];
		that.apply(ctx, args.concat(args1));
	}
}

let Person = {
	name: 'Tom',
	say(age, sex) {
		console.log(`${this.name} : ${age} : ${sex}`)
	}
}
Person1 = {
	name: 'Tom1'
}
Person.say.myApply(Person1, [18, 'male'])