1. call
call 方法使用一个指定的 this值和单独给出的一个或多个参数来调用一个函数.
function.call(thisArg, arg1, arg2…)
// 重写call/*call 方法作用:1. 改变this的指向, 指向到call的值2. 函数执行*/Function.prototype.myCall = function (context) {// 1. 获取参数, 第一项this指向不要var args = Array.prototype.slice.call(arguments, 1);let result = null;// 2.判断是否传入 上下文, 没有则指向windowcontext = context || window;// 3. 将调用的方法挂载到 context,context.fn = this;// 执行要调用的方法result = context.fn(...args);// 从上下文中删除添加的 属性方法delete context.fn;// 返回结果return result}
2. apply
apply call唯一的区别是, apply的参数使用数组进行传递.
Function.prototype.myApply = function (context) {var result = null;context = context || window;const fnSymbol = Symbol();context[fnSymbol] = this;result = context[fnSymbol](...arguments[1]);delete context[fnSymbol];return result;}
3. bind
bind 改变 this指向, 返回一个新的函数, 但是不执行.bind挂载在 Function.prototype 上new过bind返回的函数, this指向失效.
Function.prototype.bindy = function (context) {var _self = this;var args = Array.prototype.slice.call(arguments, 1);var tempFn = function () {};var fn = function () {var newArgs = Array.prototype.slice.call(arguments);// new -> this -> fn{} -> __proto__ -> Person// no new -> window_self.apply(this instanceof _self ? this : context, args.concat(newArgs));}// 圣杯模式tempFn.prototype = this.prototype;fn.prototype = new tempFn();return fn;}
