2009-06-26 84 views
0

爲什麼這樣不行?爲什麼說xxx不是函數

aContract = function(){}; 
aContract.prototype = { 
    someFunction: function() { 
     alert('yo'); 
    }, 
    someOtherFunction: some$Other$Function 
}; 

var some$Other$Function = function() { 
    alert('Yo yo yo'); 
}; 

var c = new aContract(); 
c.someFunction(); 
c.someOtherFunction(); 

螢火蟲說c.someOtherFunction不是一個函數

但是,這只是正常

aContract = function(){}; 
aContract.prototype = { 
    someFunction: function() { 
     alert('yo'); 
    }, 
    someOtherFunction: some$Other$Function 
}; 

function some$Other$Function() { 
    alert('Yo yo yo'); 
}; 

var c = new aContract(); 
c.someFunction(); 
c.someOtherFunction(); 

缺少什麼我在這裏???我更喜歡使用第一種方法在JavaScript中編寫代碼,這種方法通常可以正常工作,但在原型時似乎不能正確工作。在沙地Eggo

回答

3

感謝, 〜CK已分配給some$Other$FunctionaContract.prototype.someOtherFunction實際創建some$Other$Function之前。聲明的順序很重要。如果切換事物的秩序,你會好:

var some$Other$Function = function() { 
    alert('Yo yo yo'); 
}; 

aContract = function(){}; 
aContract.prototype = { 
    someFunction: function() { 
     alert('yo'); 
    }, 
    someOtherFunction: some$Other$Function 
}; 
4

在這個被評爲時間:

aContract.prototype = { ... } 

這還未計算:

var some$Other$Function = function() { ... } 

因此aContract.prototype.someOtherFunction設置爲undefined

第二個原因是因爲函數聲明(其中第一個是表達式)在任何其他語句之前被評估。這裏有更多詳細信息:Named function expressions demystified

0

看起來,在全局範圍內,var的工作方式與在函數本地範圍中的工作方式不同。在函數本地範圍中,var聲明的變量被提升到函數的頂部(即,在關鍵字爲var的函數內的任何地方聲明的任何變量都可在該函數的其他任何位置使用)。但在全局範圍內,也許只有使用關鍵字function來聲明一個變量纔會產生相同的結果(即使用關鍵字function聲明的變量將在該全局範圍內的任何地方可用,即使在該聲明之前的行中也是如此)。

+0

這是不正確的。調用blah()顯示「undefined」:function blah(){ alert(x); var x = 5; } – 2009-06-26 23:25:59

1

這是由於吊裝。函數語句被移動到其作用域的頂部。

編輯:驗證克羅克福德的JavaScript:好的部分第113頁。

相關問題