tags:

views:

60

answers:

2
Array.prototype.clear = function(){
    this = new Array();
    return true;
}

That code raise an invalid assignment left-hand side error.

How do I change the object itself within one of his methods?

+2  A: 

You can't change the reference of what the this value points to, it is immutable.

If you want to clear the current array, you can simply set its length property to zero:

Array.prototype.clear = function(){
  this.length = 0;
  return true;
};

Edit: Looking at the comment made to the sasuke's answer, you could empty the array as in my first example, and then push the elements of another array, for example:

Array.prototype.test = function () {
  var newArray = ['foo', 'bar']; // new array elements
  this.length = 0; // empty original
  this.push.apply(this, newArray); // push elements of new array
};
CMS
I'm not sure who down-voted you but your post was more informative than mine; esp the immutability of `this` part. +1 from me.
sasuke
Thanks @sasuke :)
CMS
+2  A: 

How about:

Array.prototype.clear = function(){
    this.length = 0;
    return true;
}
sasuke
What if I want my array equals `['this array has been cleared']` after the method runs?
Erik Escobedo
@Erik, you can always check an array's length property. There should really be no need for a 'isCleared' state.
BGerrissen