箭头函数使用注意事项

js在实际应用中的小知识点

  remove(){
                var that = this;
                this.body.on("click","span",function(){
                    var index = $(this).parent().parent().attr("data-id");
                    for(var i=0;i<that.goods.length;i++){
                        if (that.goods[i].id == index) {
                            break;
                        }
                    }
                    localStorage.goods = JSON.stringify(that.goods);
                    $(this).parent().parent().remove()
                })
            }
1.localstorage模拟购物车,在给购物车写删除按钮时,曾试图在点击事件中使用箭头函数。但这种做法不可行,因为箭头函数在声明时会自动绑定上层this,它没有普通函数动态绑定this的能力,但回调函数的this指向全局window,所以此处index将是undefined。所以正确的做法是回调函数使用ES5普通函数而不是箭头函数。
2.使用foreach遍历数组不可以break,使用if可以break;

猜你喜欢

转载自blog.csdn.net/weixin_41658426/article/details/80752028