eslint外部this和function中的this

做一个功能,jquery实现很简单

$(".variant_list").find("li").each(function(){
  $(this).click(function() {
    $(this).siblings('li').removeClass('active')
    $(this).addClass('active')
    $('#product_property').val($(this).attr('data-id'))
    parentDom.priceChange($(this).attr('data-id'))
  });
});

 

但在es6中就比较麻烦

export default class CartProperty {
  static defaults = {
    actionMethod: 'POST',
    productPriceId: '#product_price',
    productNumUrl: '/api/carts/updateprice',
    productCurrentId: '#product_id',
    productNumId: '#product_num',
    productPropertyId: '#product_property'
  }

  constructor(element) {
    this.$element = $(element)
    this.options = $.extend({}, CartProperty.defaults, this.$element.data())
    // 当前显示的价格
    this.$productPriceId = $(this.options.productPriceId)
    // 当前的product id
    this.$productId = $(this.options.productCurrentId).val()
    // 当前num
    this.$productNumVal = $(this.options.productNumId).val()
    // 当前规格的隐藏域
    this.$productPropertyId = $(this.options.productPropertyId)
  }

  init() {
    this.propertyChange()
  }

  propertyChange = () => {
    this.$element.find('li').each(function () {
      $(this).on('click', () => {
        $(this).siblings('li').removeClass('active')
        $(this).addClass('active')
        $('#product_property').val($(this).attr('data-id'))
      })
    })
  }

  priceChange = (currentProperty) => {
    // ajax获取价格
    const ajaxOptions = {
      method: this.options.actionMethod,
      data: {
        number: this.$productNumVal,
        property: currentProperty,
        id: this.$productId
      }
    }
    console.log(currentProperty)

    if (this.options.actionWithToken) {
      ajaxOptions.headers = {
        Authorization: getToken(),
      }
    }
    $.ajax(this.options.productNumUrl, ajaxOptions).done((data) => {
      this.$productPriceId.html(`¥${data.price}`)

    }).fail(() => {
      window.location.href = '/login'
    })
  }
}

 

 

 

 

上面代码中的this指向了class CartProperty, 但propertyChange中each的this指向啦each的li,现在我想在click中调用priceChange,肯定使用this是调用不了的,刚开始想到啦self,但self指向了window,后来我就想需要个东西把this指引进来:

 

propertyChange = (parentDom) => {
    this.$element.find('li').each(function () {
      $(this).on('click', () => {
        $(this).siblings('li').removeClass('active')
        $(this).addClass('active')
        $('#product_property').val($(this).attr('data-id'))
        parentDom.priceChange($(this).attr('data-id'))
      })
    })
  }


这里我用parentDom把this指引进来,同样的,调用这个function的地方需要传入this

 

 

init() {
    this.propertyChange(this)
  }

 

 

 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值