call、bind、apply知识点
apply
function.apply(obj, [param1,params2,...]) // obj:要绑定的this // 第二个参数:类数组或数组,做为function的参数传入 // 当即执行
call
function.call(obj, param1, param2, ...) // obj:要绑定的this // 第二个参数:函数运行的参数,用逗号隔开 // 当即执行
bind
function.bind(obj, param1, param2, ...) // obj:要绑定的this // 第二个参数:函数运行的参数,用逗号隔开 // 返回一个函数
基本理念:借用方法,修改this
指向javascript
const params = 'ahwgs' const toString = Object.prototype.toString const type = toString.call(params) console.log('数据类型',type) // [object String]
var arrayLike = { 0: 'OB', 1: 'Koro1', length: 2 } Array.prototype.push.call(arrayLike, '添加元素1', '添加元素2'); console.log(arrayLike) // {"0":"OB","1":"Koro1","2":"添加元素1","3":"添加元素2","length":4}
借用数组的push方法,向arrayLike
中push
新数据html
call
实现Function.prototype.myCall = function(context,...arr) { if (context === null || context === undefined) { // 指定为 null 和 undefined 的 this 值会自动指向全局对象(浏览器中为window) context = window } else { context = Object(context) // 值为原始值(数字,字符串,布尔值)的 this 会指向该原始值的实例对象 } const specialPrototype = Symbol('特殊属性Symbol') // 用于临时储存函数 context[specialPrototype] = this; // 函数的this指向隐式绑定到context上 let result = context[specialPrototype](...arr); // 经过隐式绑定执行函数并传递参数 delete context[specialPrototype]; // 删除上下文对象的属性 return result; // 返回函数执行结果 }
apply
Function.prototype.myApply = function (context) { if (context === null || context === undefined) { context = window // 指定为 null 和 undefined 的 this 值会自动指向全局对象(浏览器中为window) } else { context = Object(context) // 值为原始值(数字,字符串,布尔值)的 this 会指向该原始值的实例对象 } // JavaScript权威指南判断是否为类数组对象 function isArrayLike(o) { if (o && // o不是null、undefined等 typeof o === 'object' && // o是对象 isFinite(o.length) && // o.length是有限数值 o.length >= 0 && // o.length为非负值 o.length === Math.floor(o.length) && // o.length是整数 o.length < 4294967296) // o.length < 2^32 return true else return false } const specialPrototype = Symbol('特殊属性Symbol') // 用于临时储存函数 context[specialPrototype] = this; // 隐式绑定this指向到context上 let args = arguments[1]; // 获取参数数组 let result // 处理传进来的第二个参数 if (args) { // 是否传递第二个参数 if (!Array.isArray(args) && !isArrayLike(args)) { throw new TypeError('myApply 第二个参数不为数组而且不为类数组对象抛出错误'); } else { args = Array.from(args) // 转为数组 result = context[specialPrototype](...args); // 执行函数并展开数组,传递函数参数 } } else { result = context[specialPrototype](); // 执行函数 } delete context[specialPrototype]; // 删除上下文对象的属性 return result; // 返回函数执行结果 };
bind
Function.prototype.myBind = function (objThis, ...params) { const thisFn = this; // 存储源函数以及上方的params(函数参数) // 对返回的函数 secondParams 二次传参 let fToBind = function (...secondParams) { const isNew = this instanceof fToBind // this是不是fToBind的实例 也就是返回的fToBind是否经过new调用 const context = isNew ? this : Object(objThis) // new调用就绑定到this上,不然就绑定到传入的objThis上 return thisFn.call(context, ...params, ...secondParams); // 用call调用源函数绑定this的指向并传递参数,返回执行结果 }; if (thisFn.prototype) { // 复制源函数的prototype给fToBind 一些状况下函数没有prototype,好比箭头函数 fToBind.prototype = Object.create(thisFn.prototype); } return fToBind; // 返回拷贝的函数 };