2014-04-28 103 views
1

我的代碼:如何訪問一個函數內部的變量在JavaScript

var here; 
function setNews(data2){ 
    here = data2; 
    console.log(here);//1st console log 
} 
console.log(here);//2nd console log 

在第一控制檯登錄裏面這裏有打印的數據,但在第2個控制檯登錄它打印不確定我如何可以訪問setNews函數中的數據,以便我可以在setNews之外使用它。

謝謝。

+0

Acutally它應該工作,你可以通過整個代碼?我能夠重現這種行爲。 'var here; function setNews(data2){ here = data2; console.log(here); //第一個控制檯日誌 } setNews(「ff」); console.log(here); //第二個控制檯日誌' – Praveen

+0

你把所有這些代碼放在document.ready函數中嗎?我認爲當你把所有的東西放在document.ready之外時,你的代碼應該可以工作。試試看。 –

+1

你在哪裏調用函數setNews? – Eddie

回答

1
var here; 
function setNews(data2){ 
    here = data2; 
    console.log("inside function " +here);//1st console log 
} 
setNews("something"); 
console.log("outside function" +here);//2nd console log 

Fiddlehttp://jsfiddle.net/bmArj/

2

可能您需要檢查您的架構。

var here; 
function setNews(data2){ 
    here = data2; 
    console.log(here);//1st console log 
} 
//executed immediatly, `here` is not yet initialized by setNews 
console.log(here);//2nd console log 

變「這裏」是被輸出到的JavaScript加載immedialy當控制檯,但因爲它是不確定的,控制檯顯示「未定義」。

當你以後調用setNews('sample')時,它會設置全局變量here,但是沒有意義,因爲它已經被輸出了。

0

//將其初始化爲期望的值。

var here = "your value"; 
0

我想......使用回...

var here = setNews(2); 

function setNews(data2){ 
    here = data2; 
    console.log(here);//1st console log 

    return here; 
} 
console.log(here);//2nd console log 
0

請閱讀這篇文章JavaScript Variable and Function Hoisting

發生了什麼事是當你第一次聲明變量here,它沒有被初始化。 如果here的值在功能setNews()的內部,則其值不可用於外部console.log。 所以你需要調用setNews()首先在第二個電話顯示的here內容到控制檯前,像這樣:

var here; 
function setNews(data2){ 
    here = data2; 
    console.log(here);//1st console log 
} 
setNews("some data here"); 
console.log(here);//2nd console log, it will display "some data here" 
0

如果要定義一個變量,(我們稱之爲「這裏」)是自動設置爲一些名爲「setNews」的函數的值,那麼這可能會更好地工作:

var here, 
    data2 = "the news!"; 

// Set value of "here" to processed data2 
here = (function (news) { 
    // Process news 
    news = "This is " + news; 
    return news; 
})(data2); 

console.log(here); 
// Prints "This is the news!" 
相關問題