rubixibuc
rubixibuc

Reputation: 7417

Deleting Reference to Object in Different Context

I am implementing a binary tree in JavaScript and need to be able to pass a variable to a function, and set the value of the variable within it's initial context to undefined from inside the function.

Example:

var foo = {}

function bar(a) { a = undefined }

bar(foo)

In this context, foo is still defined.

I realise this won't work like this, but how can I do something similar in JS? Also, foo won't always be global.

Upvotes: 1

Views: 45

Answers (1)

user113716
user113716

Reputation: 322542

If foo is global, you can pass the name as a string, and access it as a property of the global object.

In a browser, you'd use window:

var foo = {};

function bar(a) { window[ a ] = undefined; }

bar('foo');

alert( foo ); // undefined

If foo isn't global, I don't think you'll be able to do it without using .eval().

Upvotes: 1

Related Questions