How to write a mutator method in javascript?
Array.prototype.clear = function(){
this = new Array();
return true;
}
That code raise an invalid assignment left-hand sid开发者_如何学编程e
error.
How do I change the object itself within one of his methods?
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
};
How about:
Array.prototype.clear = function(){
this.length = 0;
return true;
}
精彩评论