【发布时间】:2020-08-26 07:47:38
【问题描述】:
我在 js 中实现了一个拖放界面,它有两个对象表和一个作为源或目标的对象。为了执行“移动”操作,我想到了使用这两个类方法:
_getVar(id) {
var ind;
switch (id[0]) {
case 'c':
return this.clipboard;
case 's':
ind = Number(id.substr(1)) - 1;
return this.SynthPatches[ind];
case 'f':
ind = Number(id.substr(1)) - 1;
return this.FilePatches[ind];
}
}
move(from, to) {
var fv = this._getVar(from);
var tv = this._getVar(to);
if (fv == undefined) return "Source empty";
if (tv == undefined) return "Destination undefined";
tv = fv;
return "Ok";
}
这不起作用。 fv 和 tv 是对正确对象的本地引用。参考 fv 被复制到 tv 然后两者都被遗忘了。 我想要一个类似于 python 中的深拷贝的东西,但看起来唯一的解决方案是内联 _getVar() 九次,这使得代码非常难看。
【问题讨论】:
-
tv = fv;不会像您期望的那样运行,它只会为局部变量 tv 分配 fv 的值,因此 tv 将不再指向它的原始对象,并且在该函数之外不会发生任何事情,您需要一个参考示例:mainObj.tv = fv;或mainObj[index].tv = fv; -
这里的挑战是,没有单一的“mainObj”。相反,从三个可能的 mainObjects(this.SynthPatches、this.FilePatches 或 this.clipboard)中选择一个是 _getVars 任务。
标签: javascript arrays object reference