javascript - 删除变量的值而不丢失其子方法

标签 javascript parent

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

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

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

关于javascript - 删除变量的值而不丢失其子方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9625954/

相关文章:

javascript - 用jQuery获取声卡的输入声音

javascript - Vue 列表不显示 javascript 字典的键?

javascript - 如何构建一个简单的网络切换?

jquery悬停找不到父跨度

javascript - 如何在 Three.js 中从圆柱体中挤出高度段?

javascript - 合并 2 个对象数组以创建对象映射

c - C 中后台子进程的无效命令

c++ - 如何从 dll 内部找到 dll 的父 exe?

delphi - 为什么 "ParentBackground"不适用于 Windows 经典主题? (德尔福)

css - 为什么div居中