简体   繁体   English

我可以将变量作为值分配给对象的键吗?

[英]Can I assign a variable as value to an object's key?

Is this allowed?这是允许的吗?

export class H{
passwordErrorMessage = 'Password must contain 1 small-case alphabet, 1 capital  alphabet, 1 digit, 1 special character. The length should be 6-10 characters.'
...

validatePassword(control: FormControl) {
...
    return (REG_EXP.test(password)) ? null : {
      validatePassword: { // check the class ShowErrorsComponent to see how validatePassword is used.
        valid: false,
        message:  this.passwordErrorMessage //can I do this?
      } 
    };
  }
}

For one of my test cases, I am getting the following error对于我的一个测试用例,我收到以下错误

TypeError: Cannot read property 'passwordErrorMessage' of undefined
Error object: Property name: ngDebugContext, value: [object Object]
Error object: Property name: ngErrorLogger, value: function () { [native code] }
TypeError: Cannot read property 'passwordErrorMessage' of undefined
    at HelperService.validatePassword (webpack:///./src/app/helper.service.ts?:224:31)

It seems this is undefined .似乎thisundefined I am still in early stages of debugging but my first doubt is if the usage of this is correct?我仍然在调试初期阶段,但我的第一个疑问是,如果的使用this是正确的? Things work fine if I change the usage to message: 'Password must contain 1 small-case alphabet, 1 capital alphabet, 1 digit, 1 special character. The length should be 6-10 characters.'如果我将用法更改为message: 'Password must contain 1 small-case alphabet, 1 capital alphabet, 1 digit, 1 special character. The length should be 6-10 characters.'则一切正常message: 'Password must contain 1 small-case alphabet, 1 capital alphabet, 1 digit, 1 special character. The length should be 6-10 characters.' message: 'Password must contain 1 small-case alphabet, 1 capital alphabet, 1 digit, 1 special character. The length should be 6-10 characters.'

yes you can, but you'll need to either bind validatePassword to the class or use an arrow function to pass this context into the function.是的,您可以,但您需要将validatePassword绑定到类或使用箭头函数this上下文传递到函数中。 this should work:这应该有效:

export class H{
    passwordErrorMessage = 'Password must contain 1 small-case alphabet, 1 capital  alphabet, 1 digit, 1 special character. The length should be 6-10 characters.'
    ...

    validatePassword = (control: FormControl) => {
        ...
        return (REG_EXP.test(password)) ? null : {
          validatePassword: { // check the class ShowErrorsComponent to see how validatePassword is used.
            valid: false,
            message:  this.passwordErrorMessage
          } 
    };
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM