删除变量's的价值而不丢失其子方法

Removing a variable's value without losing its children methods

本文关键字:子方法 变量 删除      更新时间:2023-09-26

我正在尝试删除数组的值,而不删除其方法。考虑以下代码:

var Project = function () {
    //The array where all data will be stored before they are sent..
    this.data = [];
    // ... Along with a function to send data to other source ...
    this.data.send = function () {
    }
    //Here is where the data would be altered ...
    //Send the data ...
    this.data.send();
    //Remove the data, we don't want it when sending the next time ...
    this.data = [];
    // ... but this (obviously) results in the removal of the send() function ... :-(
}

这也将删除函数.send(),这不是我想要的行为。回避这个问题最顺利、最恰当的方法是什么?谢谢

Sirko的建议应该有效,但在我看来,您的问题指向了设计缺陷。

为什么不公开一个类似数组的对象,方法永远不会改变,但有一个可以随意操作的内部数组。

var data = {
  items: [],
  push: function(item) {
    this.items.push(item);
  },
  send: function() {
    // send the items
    this.items = [];
  }
}
data.push('abc');
data.send();
console.log(data.items.length) // 0

让数组成为数组,并使用其他构造来操作它们。

使用this.data = [];,您可以用新的数组对象替换旧的数组对象,从而丢失所有附加的函数。必须修改现有对象才能保留特性。例如,您可以使用splice(docu@MDN):

this.data.splice( 0, this.data.length );

或者,正如Elliot Bonneville建议的那样,您可以将长度设置为零(again@MDN)

this.data.length = 0;

您可以执行以下操作:

this.data.length = 0;

然后,您现有的数组将为空,并保留所有其他属性。这里有一个关于使用javascript数组的有趣参考。