2014-03-30 53 views
-1

我使用下面的代碼:無法訪問數組中的JavaScript

function Cal() { 
    this.currectnum =[5]; 
    this.bool_num = false; 
    this.C=C; 
    this.alltimetext = new toString; 
    this.addnum = addnum; 
    this.equel = equel; 

function C() { 
    update(0); 
    this.bool_num= true; 
    this.alltimetext="0"; 
    console.log(this.currectnum); 
} 

function update(value) { 
    cur = document.getElementById("screen_p"); 
    cur.innerHTML = value; 
    console.log(this.currectnum); 
} 

我不明白,爲什麼當我按第C我的日誌:

undefined 
[5] 

爲什麼C()可以「看到「數組但是update(value)不能?

回答

1

當您在「C」中調用「更新」時,您不需要確保this將具有正確的值。嘗試

update.call(this, 0); 

改爲。這將確保在「更新」功能中,this的值與「C」中的值相同。

當您調用沒有任何上下文對象的函數時,該函數中的值this將是全局上下文或(在「嚴格」模式下)undefined

+0

嗨,謝謝! 你可以請explin爲什麼呢? – user3436708

+0

@ user3436708我嘗試在答案中解釋。 'this'的值由函數調用的方式決定。當你調用'update(0)'時,該函數中this的值將是全局對象('window')或'undefined'。這就是JavaScript的工作原理。 – Pointy

+0

actulley我明白非常好,非常感謝。 – user3436708