call apply 原理的实现
- 在项目的入口文件 App.vue 中加入下列代码实现刷新缓存vuex中数据的目的
let person1 = {
name: '张三',
say: function (hobby) {
console.log(this.name)
console.log('爱好: ' + hobby)
}
}
let person2 = {
name: '李四'
}
Function.prototype.myCallES5 = function (context) {
function mySymbol(obj) {
let unique = Math.random() + new Date()
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
}
Function.prototype.myCallES6 = function (context) {
let uniqueName = Symbol(context)
let args = Array.from(arguments).slice(1)
context[uniqueName] = this
let result = context[uniqueName](...args)
delete context[uniqueName]
return result
}
Function.prototype.myApplyES6 = function (context, args) {
let uniqueName = Symbol(context)
args = Array.from(arguments).slice(1)
context[uniqueName] = this
let result = context[uniqueName](...args)
delete context[uniqueName]
return result
}
person1.say('打游戏')
console.log('call')
person1.say.call(person2, '健身')
console.log('myCallES5')
person1.say.myCallES5(person2, '健身')
console.log('myCallES6')
person1.say.myCallES6(person2, '健身')
console.log('myApplyES5')
person1.say.myApplyES5(person2, ['健身','打游戏'])
console.log('myApplyES6')
person1.say.myApplyES6(person2, ['健身','打游戏'])