简体   繁体   English

获取方法在 Typescript 中返回未定义

[英]get methods return undefined in Typescript

I don't undertand what's my code error when defining the get and set methods for a private field.在为私有字段定义 get 和 set 方法时,我不明白我的代码错误是什么。

export class User{
  private userName = "defaultName";

  constructor(private token:string){}

  public get UserName():string{
    return this.userName;
  }

  public set UserName(value:string){
    this.userName = value;
  }    

  public get Token():string{
    return this.token;
  }

  public set Token(value:string){
    this.token= value;
  }
}

When I try the following code I get undefined values.当我尝试以下代码时,我得到未定义的值。

    const user:User = JSON.parse(localStorage.getItem("user"));
    console.log(user.UserName);
    console.log(user.Token);

EDIT编辑

The problem is not about the get methods .问题不在于 get 方法 I tried to read fields of a custom object (User) using data retrieved from localStorage:我尝试使用从 localStorage 检索的数据读取自定义 object(用户)的字段:

 const user:User = JSON.parse(localStorage.getItem("user"));

With that code I'm able to read public fields but not the private ones using the get methods, because when you JSON.parse data (in my case retrieved from localStorage ) you obtain a plain javascript object, even if you try to "typify" the variable this way: user:User .使用该代码,我可以使用 get 方法读取公共字段,但不能读取私有字段,因为当您JSON.parse数据(在我的情况下从localStorage检索)时,您将获得一个普通的 javascript ZA8CFDE6331BD59EB6666F891C4,即使您尝试“ " 这样的变量: user:User

I tried to access the field using the get method user.UserName that actually doens't exist on the plain javascript object I created with JSON.parse;我尝试使用 get 方法user.UserName访问该字段,该方法在我用 JSON.parse 创建的普通 javascript object 上实际上不存在; inside this plain javascript object there is only the field user.username.在这个普通的 javascript object 里面只有字段 user.username。 What I tried to do is not possible (I suppose).我试图做的事情是不可能的(我想)。

That code should work.该代码应该可以工作。 Playground操场

Why didn't your example work out?为什么你的例子没有成功?

When you parse item from local storage user variable becomes something like this: { userName: "John", token: 30 }当您从本地存储中解析项目时, user变量会变成这样: { userName: "John", token: 30 }

But you accessing user.UserName which does not exists so you have to mimic object from localStorage like so user.userName .但是您访问不存在的user.UserName ,因此您必须从localStorage模仿 object ,就像user.userName一样。

Ways to fix it:解决方法:

  1. Create new instance of the User class创建User class 的新实例

 const userFromLocalStorage = JSON.parse(JSON.stringify({ userName: "John", token: 30 })); const user = new User(userFromLocalStorage.userName, userFromLocalStorage.token) console.log(user.userName); console.log(user.token);

  1. Create getters/setters that mimic shape of object like in example below创建模仿 object 形状的 getter/setter,如下例所示

Things to consider.要考虑的事情。

  • In typescript we don't write capitalized setters or getters在 typescript 我们不写大写的 setter 或 getter
  • Use this approach for naming private variables private _userName = "defaultName";使用这种方法命名私有变量private _userName = "defaultName"; with underscore带下划线
  • Doing this constructor(public token:string){} you don't have to create setters or getters.执行此constructor(public token:string){} ,您不必创建 setter 或 getter。

 export class User{ private _userName = "defaultName"; constructor(username, public token:string){ this.userName = username; } public get userName():string{ return this._userName; } public set userName(value:string){ this._userName = value; } } const user: User = JSON.parse(JSON.stringify({ "userName":"John", "token":30 })) console.log(user.userName); console.log(user.token);

Typescript documentation Typescript 文档

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

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