JS实现call,apply,bind函数

实现之前的预备知识

  • ...用作展开
  • ...用作剩余参数
  • Object.create()的作用
  • 原型链与构造函数

这些有时间补上吧

call函数实现

Function.prototype.myCall = function (obj, ...args) {
	obj = obj || window;
	obj.fn = this;
	let result = obj.fn(...args);
	delete obj.fn;
	return result;
};

apply函数实现

Function.prototype.myApply = function (obj) {
	let context = obj || window;
	let result;
	context.fn = this;
	if (arguments[1]) {
		result = context.fn();
	} else {
		result = context.fn(...arguments[1]);
	}
	delete context.fn;
	return result;
};

bind函数实现

Function.prototype.mbind = function (obj, ...args) {
	let self = this;
	let bound = function () {
		self.apply(obj,args);
	};
	bound.prototype = Object.create(self.prototype, {
		constructor: {
			value: self,
		},
	});
	return bound;
};

如有错误还请指正

posted @ 2020-08-13 11:20  S·QING  阅读(313)  评论(0)    收藏  举报