删除变量's的价值而不丢失其子方法
Removing a variable's value without losing its children methods
我正在尝试删除数组的值,而不删除其方法。考虑以下代码:
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数组的有趣参考。
相关文章:
- javascript从子方法调用父方法
- JS对象文字中的方法和子方法
- 面向对象的 JavaScript 共享方法变量
- 从子方法访问父对象
- 如何从子方法调用父方法
- 在 dojo 中使用它通过父类访问子方法
- 从匿名函数层内访问方法变量
- 带有构造函数的Javascript子方法/名称空间
- 用于区分节点JS中模块/实例/方法变量的命名约定
- 删除变量's的价值而不丢失其子方法
- Webstorm原型函数中未解析的方法/变量
- 如何避免CoffeeScript方法变量被包裹在对象文字中
- 用子方法实现函数可以吗
- 我如何从父调用原型子方法
- 从子方法访问父属性
- 带有子方法的方法链接
- 将不断变化的属性值设置为子状态变量
- 访问骨干视图(解析视图)中的方法变量
- 自动css选择器生成的第n子方法的替代方案
- 在Javascript中从子方法调用父方法