1、js手写call(不能使用ES6语法)复杂
Function.prototype.myCall = function(context){
if (context === null || context === undefined) {
context = window
} else {
context = Object(context)
}
console.log('this',this)
function mySymbol(obj){
let unique = (Math.random()+new Date().getTime())
if(obj.hasOwnProperty(unique)){
return mySymbol(obj)
}else{
return unique
}
}
let uniqueName = mySymbol(context)
let args = []
for(let i = 1; i < arguments.length; i++){
args.push('arguments[' + i + ']')
}
context[uniqueName] = this
let result = eval('context[uniqueName](' + args.join(',') + ')')
delete context[uniqueName]
return result
}
2、js手写call(使用ES6语法)简单
Function.prototype.myCall = function(context,...args){
if (context === null || context === undefined) {
context = window
} else {
context = Object(context)
}
let fn = Symbol('唯一的值')
context[fn] = this
let result = context[fn](...args)
delete context[fn]
return result
}