eval对函数this指向的影响
js eval() 对 this 指向的影响
const fn = () => {
console.log('fn this is:', this)
}
function evalWrapper(str) {
console.log('eval wrapper this is: ', this)
return eval(str)
}
const fn2 = evalWrapper(fn.toString()) // Window
const fn3 = evalWrapper.bind({ a: 1 })(fn.toString()) // Object { a: 1 }
fn() // Window
fn2() // Window
fn3() // Object { a: 1 }
eval返回的函数, 即使是箭头函数, this指向也不随着调用者变更, 这与箭头函数this指向随着调用者而改变不符, 原因不详
以下是更详细的验证过程:
const fn = () => {
console.log('fn this is:', this)
}
function evalWrapper(str) {
console.log('eval wrapper this is: ', this)
return eval(str)
}
function execute(fn) {
console.log('execute this is:', this)
fn()
}
const anotherThis = { a: 1 }
console.log('生成fn2, fn3')
const fn2 = evalWrapper(fn.toString())
const fn3 = evalWrapper.bind(anotherThis)(fn.toString())
console.log('直接执行fn, fn2, fn3')
fn()
fn2()
fn3()
console.log('改变this指向后调用fn, fn2, fn3')
execute.bind(anotherThis)(fn)
execute.bind(anotherThis)(fn2)
execute.bind(anotherThis)(fn3)
PS: 如果可以不使用eval, 请不要使用eval