【问题标题】:Cannot update class variable when returning method call with parameters返回带参数的方法调用时无法更新类变量
【发布时间】:2017-05-22 10:04:04
【问题描述】:

当用户单击按钮时,我正在尝试更新轮播类中的变量。由于我还需要在某个阶段更新另一个变量,我希望“cycleThrough”方法接受参数:

但是,当使用参数时,它不会更新我的变量。如果我用实际变量替换方法中的参数,它确实有效。

import $ from "jquery";

class carousel {

    constructor() {
        this.varOne = 0;
        this.len = 3;

        this.updateOnClick();
    }

    updateOnClick() {
        const that = this;
        $(".testButton").click(function(){          
            that.cycleThrough(that.varOne, that.len); 
        });
    }

    cycleThrough(toCycle, forLength) {
        if(toCycle > forLength) {    
            return toCycle = 0;
        } else {
            return toCycle++;
        }
    }

}

export default carousel;

【问题讨论】:

  • 它似乎对我有用,我只添加了一个console.log 来输出cycleThrough 的结果:jsfiddle.net/o665pwqj/4
  • 我不得不更新 cycleThrough 方法中的变量以匹配参数,但我仍然没有得到 this.len 变量来更新。我很欣赏这不是解决此问题的最佳方法,但从学术角度来看,为什么这行不通?
  • 如果你想增加varOnelen,那么你需要实际增加那些references。当您调用 that.cycleThrough 时,您传递给它的参数将被复制。 references 未通过,cycleThrough 函数适用于“新”副本。不在this.lenthis.varOne 上。要更新varOnelen,您需要将其指定为@jkris 已回答或更改return toCycle 行,以便它们更新this.lenthis.varOne。要解决 this 的关闭问题,只需将代码更改为:$(".testButton").click(() => { 并删除所有 that 内容

标签: javascript methods scope es6-class


【解决方案1】:

您的cycleThrough 函数返回一些内容(toUpdate),但从未使用过。状态永远不会改变。

您可以像这样更改您的 updateOnClick 函数:

updateOnClick() {
  $('.testButton').click(() => { 
    this.varOne = this.cycleThrough(this.varOne, this.len);
  });
}

但实际上,这段代码,或者说类,还可以大大改进

【讨论】:

  • 道歉; “toUpdate”变量是“toCycle”参数。
猜你喜欢
  • 2019-02-08
  • 2017-06-11
  • 1970-01-01
  • 2021-03-13
  • 2019-10-21
  • 2013-09-26
  • 1970-01-01
  • 2013-05-09
  • 2011-03-18
相关资源
最近更新 更多