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.判断是否传入 上下文, 没有则指向window
context = 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;
}