2011-08-29 48 views
4

給這段JavaScript代碼:Javascript - 如何清空底層參考?

this.underlyingReference = {name: 'joe'}; 

this.nullMe(this.underlyingReference); 

alert(this.underlyingReference.name); 

function nullMe(variable) { 
    variable = null; 
} 

有沒有在Javascript中對我的方式爲空this.underlyingReference使用「變量」?我希望能夠清空變量並將底層引用清空,而不是簡單地將引用引用爲空。

我已閱讀過關於Javascript的通過引用功能的文章,如http://snook.ca/archives/javascript/javascript_pass,但它看起來好像當你想銷燬底層引用時,行爲並不是我期望從引用中得到的結果。

當執行通過第二行代碼時,我想「this.underlyingReference」被清除。然而,警戒線顯示底層引用仍然存在並且踢腿。

+4

JavaScript總是按價值傳遞。令人困惑的是,有時候這個價值是一個參考。 –

+1

@MattGreer:任何對象(這是相當多的)通過引用傳遞。 – jAndy

+0

通過值傳遞對象的引用。 –

回答

3

您可以嘗試

function nullMe(obj, reference){ 
    delete obj[reference]; 
} 

nullMe(this, "underlyingReference"); 

或者

function nullMe(reference){ 
    delete this[reference]; 
} 
nullMe.call(this, "underlyingReference"); 
4

爲什麼不直接指定爲null,該屬性:

this.underlyingReference = null; 
alert(this.underlyingReference);// null 

,或者如果你想摧毀的財產,你可以使用刪除:

delete this.underlyingReference; 
alert(this.underlyingReference);// undefined 

如果你仍然想有一個函數調用,您可以使用此設置:

var NullMe = function(obj, propName) 
{ 
    obj[propName] = null; 
    //OR, to destroy the prop: 
    delete obj[propName]; 
} 
NullMe(this, 'underlyingReference'); 
3

還有就是「按引用舊」之間的混亂,帕斯卡和使用C在某些情況下,以及java,javascript和最新編程語言中的「通過引用」。

在javascript中,傳遞了一個值,並且該值是對該對象的引用。這意味着您可以更改該引用之後的對象,但不能更改引用本身。

如果你需要做的是,在一個方法,那麼你需要做的是「明確的」,例如:

this.nullMe("underlyingReference"); 
this.nullMe = function(name) { 
    this[name] = null; 
} 

但它是一個有點,好,過工程有設置方法空:)

+0

我的實際代碼中沒有nullMe方法,這只是問題的最小可重現版本。 – omatase

+0

+1的解釋。另一方面,使用'this [name]'的建議... –