1.实现 call
Function.prototype._call = function (thisArg, ...args) {
thisArg = (thisArg !== null && thisArg !== undefined) ? Object(thisArg) : window
const symbolFn = Symbol(+new Date)
Object.defineProperty(thisArg, symbolFn, { get: () => this, configurable: true })
const result = thisArg[symbolFn](...args)
delete thisArg[symbolFn]
return result
}
const lain = {
name: 'lain',
age: 16,
friends: []
}
function foo(...newFriends) {
console.log(newFriends)
this.friends.push(...newFriends)
console.log(this)
}
foo._call(lain, '小鸟游六花', '樱岛麻衣', '伊莉雅')
2. 实现 apply
Function.prototype._apply = function (thisArg, argArray = []) {
thisArg = (thisArg !== undefined && thisArg !== null) ? Object(thisArg) : window
const symbolFn = Symbol(+new Date)
Object.defineProperty(thisArg, symbolFn, { get: () => this, configurable: true })
const result = thisArg[symbolFn](...argArray)
delete thisArg[symbolFn]
return result
}
const lain = {
name: 'lain',
age: 16,
friends: []
}
function foo(...newFriends) {
console.log(newFriends)
this.friends.push(...newFriends)
console.log(this)
}
foo._apply(lain, ['小鸟游六花','樱岛麻衣','伊莉雅'],'saber')
3.实现 bind
Function.prototype._bind = function (thisArg,argArray) {
thisArg = (thisArg !== undefined && thisArg !== null) ? Object(thisArg) : window
const symbolFn = Symbol(+new Date)
Object.defineProperty(thisArg, symbolFn, { get: () => this, configurable: true })
return (...args) => {
const result = thisArg[symbolFn]([...argArray, ...args])
delete thisArg[symbolFn]
return result
}
}
const lain = {
name: 'lain',
age: 16,
friends: []
}
function foo(newFriends) {
console.log(newFriends)
this.friends.push(...newFriends)
console.log(this)
}
foo._bind(lain, ['小鸟游六花', '樱岛麻衣', '伊莉雅'])('五河琴里')