考察call()、bind()、apply()的用法,改变this的指向
函数中this原本指向是windows,通过以下方法改变this指向
1.apply()
function bindThis(f, oTarget) {
return function() {
return f.apply(oTarget, arguments) }
}
2.bind()
function bindThis(f, oTarget) {
return f.bind(oTarget)
}
call()
function bindThis(f, oTarget) {
return function() {
return f.call(oTarget, ...arguments)
}
}
例:
function fn(x, y) {
console.log(this)
console.log(x + '-' + y)
console.log(this.name + '-' + this.age)
}
var persoon = {
name: 'chen',
age: 18
}
fn.call(persoon, 'hh', 20) //改变this指向person