最近经历了比较多的面试,发现有很多手写实现什么的,于是贴上来给大家分享一下
P.S. 吐槽一下 大家一定不要因为一些原因就放弃了提升自己学历的机会 不然会非常的后悔 像博主一样缺少了一块重要的敲门砖
// apply的实现依靠call就可以了 不需要再重复的实现
Function.prototype.myApply = function(context, arg) {
return this.myCall(context, ...arg)
}
// 其实还是有很多的边界情况的 这里我们就简单的实现 不再去判断context为基础类型之类的情况了 大家其实明白原理即可
Function.prototype.myCall = function(context, ...arg) {
if (typeof this !== 'function') {
throw new TypeError('Error') //这里其实是为了排除这种状况Function.prototype.myCall.call(sthNotAFuntion, ...args)
}
const symbolFn = Symbol('fn') // 这里使用symbol是为了不会因为挂载同名属性而误删了对象原本的属性和方法
let result = undefined
context[symbolFn] = this
if (arg.length) {
result = context[symbolFn](...arg)
} else {
result = context[symbolFn]()
}
delete context[symbolFn]
return result
}
/* new 的原理就是新生成了一个对象
* 链接到原型
* 绑定 this
* 执行结果为对象就返回结果 否则就返回开始创建的新的对象
*/
function myNew(constructor, ...arg) {
let obj = {}
obj.__proto__ = constructor.prototype
let result = constructor.apply(obj, arg)
return result instanceof Object ? result : obj
}
Function.prototype.myBind = function(context, ...arg) {
if (typeof this !== 'function') {
throw new TypeError('Error')
}
const _this = this
return function F(...args) {
if (this instanceof F) { // 这里是被作为构造函数使用时的处理逻辑
return new _this(...arg, ...args)
}
return _this.call(context, ...arg, ...args) // 网上很多用了apply 然后concat两个参数的方式 其实是有些问题的
// 例如 [].concat([1, 2], [2, 3]) [1, 2, 2, 3] 参数会散开 这里我个人更推荐使用这种方式
}
}
面试之路也是道阻且长啊 大家且行且珍惜 希望我的微薄经验能帮助到你 祝大家早日拿到合适的offer
