如何在javascript中编写mutator方法?

Eri*_*edo 1 javascript

Array.prototype.clear = function(){
    this = new Array();
    return true;
}
Run Code Online (Sandbox Code Playgroud)

该代码引发invalid assignment left-hand side错误.

如何在其中一种方法中更改对象本身?

CMS*_*CMS 5

您无法更改this指向的引用,它是不可变的.

如果要清除当前数组,只需将其length属性设置为零:

Array.prototype.clear = function(){
  this.length = 0;
  return true;
};
Run Code Online (Sandbox Code Playgroud)

编辑:看看对sasuke的回答所做的评论,你可以像我的第一个例子那样清空数组,然后push是另一个数组的元素,例如:

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
};
Run Code Online (Sandbox Code Playgroud)