- 使用call方法改变this方法
// 改变this的指向call方法
let bar = {
myname: 'barname',
test:1
}
function fn() {
this.myname = 'fnmyname'
}
fn.call(bar)
console.log(bar)//{myname: "fnmyname", test: 1}
console.log(bar.myname) //fnmyname
console.log(myname) //myname is not defined
- 通过对象的方式改变函数里的this的指向
var obj = {
myage:18,
objfn:function() {
console.log(this)//{myage: 18, objfn: ƒ}
}
}
obj.objfn()
网友评论