2016-05-16 104 views
-1

我注意到,如果我創造這樣的事情函數構造函數是否可以包含非此變量?

var j = function(){ 
this.name = "Joe", 
var no = "23" //--->statement 2 
} 

我得到的錯誤 VAR沒有=「23」 ^^^

SyntaxError: Unexpected token var 
    at Object.exports.runInThisContext (vm.js:53:16) 
    at Object.<anonymous> ([stdin]-wrapper:6:22) 
    at Module._compile (module.js:541:32) 
    at node.js:328:29 
    at _combinedTickCallback (internal/process/next_tick.js:67:7) 
    at process._tickCallback (internal/process/next_tick.js:98:9)  

我明白,一個構造函數應該使用「這「與變量,但我很好奇,爲什麼我得到一個錯誤在聲明2

回答

5

你的意思是呢?

var j = function(){ 
this.name = "Joe"; 
var no = "23"; 
} 

請注意分號,而不是逗號後的「喬」。無論如何,這個分號是可選的。你可以放棄它。

+0

你也可以解釋爲什麼添加'j(); console.log(j.no);'返回undefined? –

+0

因爲'no'不是'j'的屬性,它是構造函數中的一個變量,它不可從外部獲得。 –

+0

我如何知道它的屬性? –

相關問題