题解 | #修改 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

全部评论

相关推荐

三分入剑:我觉得还是学历问题 如果你真的想要进大厂不想在小厂的话读个211得研究生吧 我感觉简历还没你好呢 我都实习了俩月了 我投了一百多份能投出20多份简历 能面试六七次 我们部门只招研究生了都 现在连9本都很难找到像样的大厂了 你又没打过rm这种 我觉得想要进步的话就考个研究生吧
点赞 评论 收藏
分享
评论
5
收藏
分享

创作者周榜

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