How to destroy property of an object dynamically?

Asked

Viewed 203 times

1

I’m implementing a chain of responsabilities, and, when the desired object is returned, it continues with the instances of the items after it:

const ITEM_SELECIONADO = "EXEMPLO"

export interface ChainModelo{
  setNext(modelo: ChainModelo);
  next();
}

export class ExemploChain{
  modelo: ChainModelo | null;
  name:string = 'EXEMPLO';

  setNext(modelo: ChainModelo){
    this.modelo = modelo;
  }

  next(){
    if(ITEM_SELECIONADO !== name)
      return modelo.next();
    return this;
  }
}

In short, instances of various useless objects are stored in memory until the object is destroyed. To get around the problem, I modified the method next to possess the following behaviour:

next(){
  if(ITEM_SELECIONADO !== name)
    return modelo.next();
  this.modelo = null;
  return this;
}

But what I wanted was for this property to be destroyed, that it could no longer be accessed, as if it didn’t even exist. There is a way to remove a property or behavior from an object in Typescript or Javascript?

1 answer

3


You can use the delete to remove object properties:

next(){
  if(ITEM_SELECIONADO !== name)
    return modelo.next();
  delete this.modelo;
  return this;
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.