【问题标题】:Why cannot I access field in a method of same class为什么我不能访问同一类方法中的字段
【发布时间】:2018-07-31 02:57:21
【问题描述】:

以下是我的组件代码的一部分

export class RootComponent{
iSActive = true;

  setVal(j){
     if(j==0){
        isActive = false;
     }
  }

}

我是 Angular 的新手,我的问题可能听起来很傻。我的问题是为什么我不能在同一类的方法中使用/设置字段isActive,例如setVal

【问题讨论】:

  • this.isActive = false;
  • @R.Richards 那是正确的,你能写下答案并附上解释,以便我接受
  • 在引用类属性/方法时始终使用this。只有当声明的 var (let, const) 在函数范围内并且使用导出函数时,您才会在没有 this 的情况下使用它们。

标签: angular typescript angular-components


【解决方案1】:

为了从类函数中更改类级别变量的值,您需要使用this 关键字。 this 用于告诉函数在更改变量值时使用什么范围。没有它,作用域实际上就在函数内部。

例如:this.isActive = false;

【讨论】:

    【解决方案2】:

    使用 this 访问以下变量/字段

    export class rootComponent{
       iSActive = true;
    
       setVal(j){
        if(j==0){
        this.iSActive = false;
        }
     }
    
    }
    

    【讨论】:

    • 为什么会这样?访问类的当前实例?
    • 因为一个类需要这个实例来使用类作用域——所以你明白了吗
    猜你喜欢
    • 2014-03-28
    • 1970-01-01
    • 2015-05-16
    • 1970-01-01
    • 2014-12-20
    • 1970-01-01
    • 1970-01-01
    • 2019-11-17
    • 1970-01-01
    相关资源
    最近更新 更多