我正在学习 here 中的 Node 函数式编程教程。 ,但是当我尝试实现第 12 课的代码时,如下所示
function Spy(target, method) {
var store={};
var self=this;
var copy=target[method];
store[target[method]]=0;
console.log(store);
console.log(store[target[method]]);
target[method]=function(){
store[target[method]]+=1;
return copy.apply(this,arguments);
};
return {count:store[target[method]]};
}
var spy = Spy(console, 'error');
console.error('calling console.error');
console.error('calling console.error');
console.error('calling console.error');
console.log(spy.count);
我在 Spy 中得到了 console.log(store)
返回一个包含函数的对象。此外,Spy 的最终返回 return {count:store[target[method]]};
返回未定义。谁能解释一下这两者背后的原因吗?谢谢
最佳答案
因为设置store[target[method]]=0;
后您正在设置target[method]
等于一个函数,这会弄乱 store[target[method]]
的值并使其未定义。看起来您会想使用您的 copy
return
上的值:
return {count:store[copy]};
尽管这并没有帮助 count
仍将是0
在这种情况下。这是因为您返回 Spy
中的对象直接{prop: value, ...}
,因此您无法在 Spy
内真正修改它功能。尽管要绕过这个定义对象 {count:store[copy]}
作为构造函数中的变量 ( var returnObj = {count:store[copy]};
),然后返回该变量: return returnObj
。现在您可以更新returnObj.count
里面[target[method]]
.
这有效是因为 Object
JavaScript 中的 是按引用传递的。
function Spy(target, method) {
var store={};
var self=this;
var copy=target[method];
store[target[method]]=0;
var returnObj = {count:store[copy]};
target[method]=function(){
returnObj.count+=1;
return copy.apply(this,arguments);
};
return returnObj;
}
var spy = Spy(console, 'error');
console.error('calling console.error');
console.error('calling console.error');
console.error('calling console.error');
console.log(spy.count);
关于javascript - 对象字面量动态键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32731360/