题解 | #修改 this 指向#

修改 this 指向

http://www.nowcoder.com/practice/a616b3de81b948fda9a92db7e86bd171

考察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

全部评论

相关推荐

05-13 02:01
已编辑
惠州学院 前端工程师
安静的少年在求佛:建议把公司名字写到标题。以后有人想搜就能直接搜到
点赞 评论 收藏
分享
评论
5
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务