- 判断一个函数是否是异步函数
- bind方法">手写bind方法
判断一个函数是否是异步函数
const jsAsyncFunction = val => Object.prototype.toString.call(val) === '[object AsyncFunction]';isAsyncFunction(function() {}); // falseisAsyncFunction(async function() {}); // true
手写bind方法
bind() 方法创建一个新的函数,在 bind() 被调用时,这个新函数的 this 被指定为 bind() 的第一个参数,而其余参数将作为新函数的参数,供调用时使用。
语法:function.bind(thisArg[, arg1[, arg2[, ...]]])
返回值:返回一个原函数的拷贝,并拥有指定的 this 值和初始参数。
Function.prototype.myBind = function(context) {// 这里对调用者做一个判断,如果不是函数类型,直接抛异常if (typeof this !== 'function') {throw '调用必须为函数'}// 当我们调用bind函数时,我们可能传了不止一个参数// 如 fun.bind({}, arg1, arg2)// 我们需要把后面的参数拿出来let args = Array.prototype.slice.call(arguments, 1);let fToBind = this;let fNOP = function() {};let fBound = function() {return fToBind.apply(this instanceof fNOP ? this : context, args.concat(arguments));}if (this.prototype) {fNOP.prototype = this.prototype;}fBound.prototype = new fNOP();return fBound;}
fBound 函数这里有个判断 this instanceof FNOP 这个其实是为了避免一种情况,因为 bind 函数返回的是一个函数,当我们把这个函数实例化(就是new fun()),根据官方文档,当返回的函数被实例化的时候, this 指向会锁定指定该实例,不管我们传入的参数指定 this 指向。
