[英]object literal dynamic key
我在這里關注節點功能編程教程,但是當我嘗試實現第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)
返回一個包含函數的對象。 同樣,最終的返回結果為return {count:store[target[method]]};
從間諜返回未定義。 誰能解釋這兩個背后的原因? 謝謝
因為設置后store[target[method]]=0;
您將target[method]
設置為等於函數,這會弄亂store[target[method]]
並使它不確定。 看起來您將要在return
上使用copy
值:
return {count:store[copy]};
盡管這樣做無濟於事,在這種情況下, count
仍為0
。 這是因為您直接在Spy
中返回對象{prop: value, ...}
,因此您無法在Spy
函數中真正對其進行修改。 盡管為了解決這個問題,將對象{count:store[copy]}
為構造函數中的變量( var returnObj = {count:store[copy]};
),然后返回該變量: return returnObj
。 現在,您可以在[target[method]]
更新returnObj.count
。
這是Object
的,因為JavaScript中的Object
是通過引用傳遞的。
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);
我想用我在您的代碼中添加的其他日志來解釋這些內容
function Spy(target, method) {
var store={};
var self=this;
var copy=target[method]; // #0.1
store[target[method]]=0; // #0.2
console.log('Before :: store', store); // #1
console.log('Before :: target[method]', target[method]); // #2
target[method]=function(){
store[target[method]]+=1;
return copy.apply(this,arguments);
}; // #3
console.log('After :: store', store); // #4
console.log('After :: target[method]', target[method]); // #5
return {count:store[target[method]]}; // #6
}
var spy = Spy(console, 'error');
console.log(spy.count);
target[method]
是一個看起來像function () { [native code] }
用js lib編寫的某些代碼替換本機代碼)。
在0.2
您將此函數(以字符串形式)設置為store
對象的鍵,並將其值分配給0
。 因此,您的商店對象看起來像
`Before :: store { 'function () { [native code] }': 0 }`
#1
target[method]
是#2
處的本機函數。
現在,在#3
您將為target[method]
分配一個新函數,因此,從現在開始, target[method]
將引用您的新函數。
因此,在#4
您的商店對象保持不變。 (因為鍵是函數的字符串化值。)
`After :: store { 'function () { [native code] }': 0 }`
但由於您在#3
進行了賦值,因此您的target[method]
值已更改為新函數,即
After :: target[method] function (){
store[target[method]]+=1;
return copy.apply(this,arguments);
}
現在在#6
您嘗試從存儲對象中獲取一個不存在於store
對象中的鍵,這就是為什么它returns undefined
並將count的值存儲為undefined
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.