O
O
oleshkin2016-02-19 15:13:29
JavaScript
oleshkin, 2016-02-19 15:13:29

How to delete an object through a function in JS?

var person = { 
  'firstName': 'Alex',
  'lastName': 'Medvedev',
  'getFullName': function() {
    return person.firstName + ' ' + this.lastName;
  }
}

console.log(person);

// killer functions
var kill = function(obj) { // delete the object - does not work
  delete obj;
}

var kill2 = function(obj) { // replace with an empty object - does not work
  obj = {};
}

var kill3 = function(obj) { // manually delete each object property - works!
  delete obj.firstName;
  delete obj.lastName;
  delete obj.getFullName;h
}

kill(person);
console.log(person);

kill2(person);
console.log(person);

kill3(person);
console.log(person);

As you can see, only manually you can delete each property of an object, but not reset the entire object at once. I have no goals for this, I just study the language. I learned that you can call a function through another function, but was surprised when I could not nullify the object.
Is there a good practice solution here?
PS: MDN read:
https://developer.mozilla.org/en-US/docs/Web/JavaS...

Answer the question

In order to leave comments, you need to log in

4 answer(s)
L
lem_prod, 2016-02-19
@oleshkin

var kill = function(obj) { // delete the object - does not work
delete obj;
}

call kill(obj); removes an object that is in the context of the function itself, in other words, something like this happens:
there is var a = { ... };
kill(a) /* obj = a; delete obj */ in other words deletes the clone
var kill2 = function(obj) { // replace with an empty object - does not work
obj = {};
}

here the object is cleared and
the question is not deleted, why did the built-in function not please? what should happen? just delete a;
and if through the function:
function kill_obj (obj) {
detele window[obj];
}

kill_obj('str_name');

A
Alexey, 2016-02-19
@alsopub

If you just
don't like it, maybe

var kill4 = function (str) {
  eval('delete ' + str);
}

kill4('person');

M
MNB, 2016-02-19
@MNB

Object.keys(obj).forEach(function(key){
  delete obj[key];
});

N
Nicholas, 2016-02-19
@Chuv

In JS, objects are not deleted manually, this is handled by the garbage collector.
If you want to remove all enumerable properties from an object, see answer from MNB

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question