ONYX
ONYX

Reputation: 5859

javascript: How to destory class Object and make calling variable undefined?

How do I properly destroy a class object of MyClass and make the calling variable myObj = undefined?

var namespace = {};
namespace.instance = {};

function MyClass(name) {
  this.name = name;
  
  this.destroy = function() {
    delete namespace.instance[name];
  }
  
  namespace.instance[name] = this;
}

var myObj = new MyClass('test');
console.log(myObj);
myObj.destroy();
console.log(myObj) // make this undefined;

Upvotes: 0

Views: 60

Answers (1)

CertainPerformance
CertainPerformance

Reputation: 370989

In JavaScript, you cannot make a variable point to undefined without explicitly assigning undefined to the variable name. After you do

var myObj = new MyClass('test');

the only way to make myObj undefined is to do

myObj = undefined;

afterwards.

Given only a reference to the object (such as in a destroy method), there's no way to break the outer myObj reference to the object; all you can do in destroy is mutate the object, but it'll still remain an object. What you're looking for isn't really possible in JS.

Upvotes: 1

Related Questions