在做关于数据添加的方法时,需要取到当前的的id号来添加内容,而以下的this.books.some的function中的this指向的windows。
methods: {
// 添加图书
handle: function() {
this.books.some(function(item) {
if (item.id = this.id) {
item.name = this.name;
//完成更新操作后需要终止循环
return true;
}
});
}
}
所以需要取到当前的id值可以用传统的方式,在外部定义 var that=this
或者使用箭头函数也可以直接实现,由于箭头函数的this 指的是父级作用域的this。
methods: {
// 添加图书
handle: function() {
this.books.some((item) => {
if (item.id = this.id) {
item.name = this.name;
//完成更新操作后需要终止循环
return true;
}
});
}
}

本文探讨了在JavaScript中遇到的this指向问题,特别是在使用`some`方法时,this指向window而不是预期的对象。文章介绍了两种解决方案:一是传统的在外面定义`var that = this`,二是利用箭头函数保持正确的上下文。通过这两种方式,可以确保在循环内部正确地访问和修改对象属性。
542

被折叠的 条评论
为什么被折叠?



