我正在尝试删除数组的值,而不删除其方法。考虑以下代码:
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/