call & apply
Function.prototype._call()
语法:function.call(thisArg, arg1, arg2, …)
1.执行func函数,传入参数arg1, arg2, …
2.传入thisArg,强制func函数在调用时this绑定为thisArg
# 样例var Asian = {skin: 'yellow'};function Chinese() {console.log(this.skin);}Chinese._call(Asian); // yellow
往下滑见秘籍
/***** 实现原理:* Asian.fn = Chinese* Asian.fn();* delete Asian.fn* 在此基础上需要解决的问题:* 1、函数参数* 2、thisArg 参数可以传 null,当为 null 的时候,视为指向 window* 3、当执行的函数fn()有返回值时,call方法调用后也得有返回值*/// 核心思想: base 版Function.prototype._call = function (ctx, ...arg) {ctx.fn = this; // this是函数调用者 希望借用方法的借用人let result = ctx.fn(...arg); // 参数数组展开 传入函数delete ctx.fn;return result;}
完整版见:call、apply实现.js
bind
Function.prototype.bind()
function.bind(thisArg[, arg1[, arg2[, …]]])
1. 返回新的函数,不直接执行函数,手动调用新函数 => 返回新函数
2. 给调用函数的this强制绑定为thisArg => call函数
3. 传入参数 => arguments 处理 bind的参数 和 调用参数, 两次参数concat一下
4. [重点]
当 bind 返回的函数fn作为构造函数的时候,bind 时指定的 this 值失效(传入的参数不失效)
# 样例var Asian = {skin: 'yellow'};function Chinese(a, b, c) {console.log(this.skin);console.log(a, b, c);}const func = Chinese.bind(Asian);func(1, 2, 3);
base版
Function.prototype._bind = function (ctx) {var self = this; // 函数调用者 借用方法的借用人return function (...arg) {return self.apply(ctx, arg);}};
完整版见:bind实现
