1. 普通函数改变this指向
let list = {
name : "yjnb",
data : [555,666,888],
show() {
return this.data.map(function(v){
return `${this.name} - ${v}`
},this)
}
}
2. 箭头函数改变this指向
let list = {
name : "yjnb",
data : [555,666,888],
show() {
return this.data.map((v)=>{
return `${this.name} - ${v}`
})
}
}
3. bind,call,apply改变this指向
let list = {
name: '张三'
}
function User(age,url){
return console.log(age+url+this.name)
}
// call传参按顺序取,apply封装数组传参
User.call(list,18,'yjng.com')
User.apply(list,[28,'yjng.com'])
// 与call类似,但不会立即执行,需要回调
User.bind(list,38,'yjnb.com')()