1.
在js中call/apply,还有比较少用的bind;传入的第一个参数都是改变函数当前上下文对象;
call/apply区别在于传的参数不同,一个是以逗号分隔字符串,一个以数组形式。而bind和call几乎没差别只是将值返回。
可是当我们将null/undefined作为值传进去的时候呢?居然得到的是window,当前js运行环境的全局对象。
这其实在es5中就有解释的:传入null/undefined的时候将执行js全局对象浏览器中是window,其他环境是global。这样就解释得通了
将基本类型转为对应的引用类型 需要利用到它的构造函数
const a = 1;
const obj = new a.constructor(a)
console.log(obj);
call函数实现
Function.prototype.myCall = function(context,...args){
if(typeof this !== 'function'){
throw Error('caller must be a function!')
}
let _context = context
if(_context === undefined || _context === null){
_context = globalThis;
}
if(typeof _context !== 'object'){
_context = new _context.constructor(context)
}
_context.func = this
const res = _context.func(...args)
delete _context.func
return res;
}