Why am I getting this error? Uncaught TypeError: state.removeFlag is not a function

Why am I getting this error? Uncaught TypeError: state.removeFlag is not a function

问题

Uncaught TypeError: state.removeFlag is not a function

额外信息

我在使用下面的代码时遇到了问题,出现了上面的错误。我的意图很简单,我想在 'class' 中设置两个函数然后调用它们,但是我得到了上述错误并且我无法发现问题。我希望另一双眼睛可能有所帮助。我很感激你能给我的任何帮助。

注意:Flags.CROSS_SLOT 的值为 1

代码

function State(){
    this.state = 0; //bitstring representing the user's choices in the UI

    this.addFlag = function(flag){
        state = (state | flag);
    }

    this.removeFlag = function(flag){
        state = (~state | flag);
    }
}

var state = new State();

state.addFlag(Flags.CROSS_SLOT);
console.log(state.state);
state.removeFlag(Flags.CROSS_SLOT);
console.log(state.state);

您需要在函数中使用 this 关键字。另外,我个人更喜欢将函数移到对象之外并使用原型...

function State(){
    this.state = 0; //bitstring representing the user's choices in the UI
}

State.prototype.addFlag = function(flag){
    this.state = (this.state | flag);
}

State.prototype.removeFlag = function(flag){
    this.state = (~this.state | flag);
}

您正在覆盖状态变量

this.addFlag = function(flag){
    state = (state | flag); // that's the global variable defined outside
}

var state = new State();

state变量,不再是函数的新实例,而是0,您需要访问this.state而不是

this.addFlag = function(flag){
    this.state = (state | flag); // that's the global variable defined outside
}

问题是 class 中的方法正在更改您用来保存 class 实例的全局 state 变量,而不是更改 [=36] =] 在 class 中。第一次调用覆盖变量,因此第二次调用失败,因为变量不再包含对象。

Javascript 没有对象范围,因此在方法中使用 state 标识符并不意味着对象中的 state 属性。您需要使用 this 关键字来访问对象中的成员。

此外,使用 & 运算符 ro 删除一个标志并将 ~ 运算符应用于该标志,否则您将翻转所有标志并添加您试图删除的标志。

function State(){
    this.state = 0; //bitstring representing the user's choices in the UI

    this.addFlag = function(flag){
        this.state = this.state | flag;
    }

    this.removeFlag = function(flag){
        this.state = this.state & ~flag;
    }
}

演示:

// function to show values in Whosebug snippet
function log(s) { document.write(s + '<br>'); };


function State(){
    this.state = 0; //bitstring representing the user's choices in the UI

    this.addFlag = function(flag){
        this.state = this.state | flag;
    }

    this.removeFlag = function(flag){
        this.state = this.state & ~flag;
    }
}

var state = new State();

var Flags = {
  CROSS_SLOT: 1
};

state.addFlag(Flags.CROSS_SLOT);
log(state.state);
state.removeFlag(Flags.CROSS_SLOT);
log(state.state);

你可以尝试这样的事情:

function State(){
    return  {
        state: 0,
        addFlag: function(flag){
            this.state = (this.state | flag);
        },
        removeFlag: function(flag){
            this.state = (~this.state | flag);
        }
    }
}