假设我们有一个函数,里面有一个对象等等:
function myFunc() {
var obj = {
"one" : "1",
"two" : "2"
};
// And more code is down here but our main focus is in the obj object.
};
现在考虑另一个专门为 myFunc() 设计的函数,它可以在 myFunc() 中添加或删除对象 obj 的属性。例如,考虑函数 manip() 是可以在函数 myFunc() 中最小化 obj 对象的特殊函数:
manip("add", {
"three" : "3"
};
/* Now the obj object inside myFunc() becomes :
var obj = {
"one" : "1",
"two" : "2",
"three" : "3"
}
再次:
manip("remove", "one three");
/* Now the obj object inside myFunc() becomes :
var obj = {
"two" : "2"
}
那么,这可能吗?可以制作 manip() 函数吗?
最佳答案
这里的关键是
1) 将您的obj
作为函数的公共(public)属性公开
2) 实例化一个myFunc
对象
3) 将该对象传递给您的 manip
函数,以便对其进行修改
function myFunc() {
this.obj = {
one: '1',
two: '2'
};
};
function manip(item, action, parameters) {
if (action === 'add') {
return item.obj = { ...item.obj, ...parameters };
} else if (action === 'remove') {
delete item.obj[parameters];
}
}
// Instantiate a new myFunc Object
const myFuncInstance = new myFunc();
console.log(myFuncInstance.obj);
manip(
myFuncInstance,
'add',
{ three: '3' }
);
console.log(myFuncInstance.obj);
manip(
myFuncInstance,
'remove',
'two'
);
console.log(myFuncInstance.obj);
关于javascript - 是否可以创建一个可以在特定函数内操作对象的函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58469743/