基礎(chǔ)的不能再基礎(chǔ)的前端面試題 手寫(xiě)call、apply谱仪、bind
當(dāng)然 不要那么繁瑣玻熙,迅速且簡(jiǎn)潔明了的寫(xiě)出來(lái)應(yīng)該是會(huì)很加分的吧?
記錄一波疯攒。嗦随。。
call
function person(a, b, c) {
console.log(this.name)
console.log(a, b, c)
}
let demo = { name: '大神仙' }
Function.prototype.myCall = function (context, ...arg) {
context = context || window
if (typeof this != 'function') {
throw new Error('Type error')
}
//防止 context中的fn重復(fù) 使用Symbol保證唯一性
const fn = Symbol('fn')
context[fn] = this
const res = context[fn](...arg)
delete context[fn]
return res
}
person.myCall(demo, '開(kāi)心', '快樂(lè)', '笑')
apply
function person(a, b, c) {
console.log(this.name, a, b, c)
}
let demo = { name: '大神仙' }
Function.prototype.myApply = function (context = window, arg) {
if (typeof this != 'function') {
throw new Error('Type error')
}
//防止 context中的fn重復(fù) 使用Symbol保證唯一性
const fn = Symbol('fn')
context[fn] = this
let res
//判斷第二個(gè)參數(shù)是否是數(shù)組
if (Object.prototype.toString.call(arg) !== '[object Array]') {
res = context[fn](...[...arguments].slice.call([...arguments], 1))
} else {
res = context[fn](...arg)
}
delete context[fn]
return res
}
person.myApply(demo, ['開(kāi)心', '快樂(lè)', '笑'])
person.myApply(demo, '開(kāi)心', '快樂(lè)', '笑')
bind
function person(a, b, c, d) {
console.log(this.name, a, b, c, d)
}
let demo = { name: '大神仙' }
Function.prototype.myBind = function (context, ...args) {
if (typeof this !== 'function') {
throw new Error("Type Error");
}
let _this = this
//bind返回函數(shù)
return function Fn() {
// bind還可以使用new
if (this instanceof Fn) {
return new _this(...args, ...arguments)
}
return _this.apply(context, [...args, ...arguments])
}
}
person.myBind(demo, '開(kāi)心', '快樂(lè)', '笑')('哈哈哈哈')
let newPerson = person.myBind(demo, '不開(kāi)心', '傷心', '哭唧唧')
let p = new newPerson('嗚嗚嗚嗚')