2

I have an array of users. Each of these user have some context, but also some functions.

Normally, to delete one of these users, one could use users.splice(index, 1) with index being the index of interest.

However, I want to add a function remove() to each of these users, and then want to remove them by simply invoking user.remove() and this should remove the user from users.

Could this be done?

1
  • Not sure this is a good idea. Objects are references, when you remove it from somewhere, you remove a reference to that object. I would name the method user.removeFrom(users). That makes it more reusable, and more explicit. Commented Jul 17, 2014 at 21:35

2 Answers 2

2

You could add a remove-function to the prototype of the users which has access to the users-array (via closure or other references).

var users = [];
User.prototype.remove = function() {
    var index = users.indexOf(this);
    users.splice(index, 1);
}
Sign up to request clarification or add additional context in comments.

6 Comments

Wouldn't that be a memory leak?
watch out for usage of indexOf < ie 9 stackoverflow.com/questions/11544983/…
@SteveHollasch: If aUser.remove() is called, aUser is removed from the users-array. When there is no other reference to aUser, the GC will collect it because there is no way to access the instance. As long as the User.prototype exists, the users-array itself is probably never collected by the GC, because the User.prototype.remove-function could always access the array. But I don't think this is a memory leak since the array will be empty if all users were removed. Correct me if I'm wrong.
@Ottis: Yes, I think you're right. Removing a user from the array will delete one reference in the loop, which makes the user available for garbage collection. I didn't think this all the way through.
@Otts— users is a global variable, so will not be garbage collected until the global execution context in which it exists expires (e.g. a new page is loaded). However, the object it references might be garbage collected sooner. User.prototype.remove only holds a reference to users for a very short time after the function is called and while it's executing, the identifier is resolved anew each time the function is called. It does not hold a reference beyond the execution of the function so should not create a "memory leak".
|
0
 //More generic
    var a= {} , b = {};
    var users = [a,b];
    Object.prototype.removeFromArray = function(users) {
        var index = users.indexOf(this);
        users.splice(index, 1);
    }
    console.dir(users); // a,b 
    a.removeFromArray(users);
    console.dir(users); //b

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.