Z
Z
zlodiak2020-05-01 11:58:38
typescript
zlodiak, 2020-05-01 11:58:38

Why doesn't the decorator remove the property?

I instantiate a class and use a decorator to try to remove a property:

function format(target: Object, propertyKey: string) {
  delete this[propertyKey]
}

class User {
  @format
  name: string
  constructor(name: string) {
    this.name = name
  }
  print(): void {
    console.log(this.name)
  }
}

let tom = new User('Tom')
tom.print()


But as a result of calling the print() method, the value of the name property is still displayed in the console. Please explain how to remove it. To make it impossible to use print() to display it

DEMO

Answer the question

In order to leave comments, you need to log in

1 answer(s)
Y
yungvldai, 2020-05-03
@yungvldai

You cannot access this in a decorator method, because at the moment when the logic that you have included in this method is working out, by definition there are no class instances, and hence the this contexts of these instances. In your example, you are trying to remove a property on the propertyKey string from a Window.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question