开发者

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;
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜