這裏是我的使用情況:如何將引用變量設置爲null?
上Phaser.io,當用戶打一個按鈕,我設置了Phaser.sprite到本地let newSquare
變量,我把它.push()
到Squares
陣列Phaser.sprite的。
後來我打電話給那個newSquare
變量的一些destroy
函數,然後我把它設置爲null。雖然精靈從屏幕的.destroy()
好後取出,我仍然可以從我的Squares
數組訪問...
我認爲,作爲如果我設置newSquare
變量設置爲null一個對象,它會被設置對於所有其他引用也爲null,不應該嗎?
那麼,爲什麼我的Squares
數組中的ref未設置爲空?
摘錄:
eventFunction (e, i) {
let newSquare = Game.add.sprite(Lines.attack.a, 0, 'square');
// Some other methods call here
Squares[ e.target.dataset.line ].push(newSquare);
setTimeout(() => {
if (newSquare) {
newSquare.destroy();
newSquare = null;
console.log(Squares); // will print an array with an iteration corresponding to newSquare object, when I want it to be set to null, in order to clean the array with a _.pull()
}
}, (2 * 1000));
}
缺少什麼我在這裏?謝謝。
不是真的。你可以有多個對同一個「事物」的引用。將其中一個引用設置爲null不會使其他引用無效。但是調用'.destroy()'會使它們失效。你明確地銷燬了這個對象,這意味着其他任何使用這些其他引用的東西現在都會嘗試使用它們的「指針」來銷燬一個對象。這就好像在你的房子周圍放了三張紙條,上面寫着「抽屜裏的襪子在牀下」。如果你燒了其中的一個帖子,你的抽屜裏仍然會有襪子。但如果你焚燒抽屜,這些筆記仍然會說那裏有襪子。 –
@MarcB我不知道在Phaser中究竟有'.destroy'的功能,但我想象一個更好的比喻是關閉並鎖定襪子抽屜。所以它仍然存在,所有的跡象仍然指向它,它可能仍然有襪子,但你不能到達它們。 – vlaz