2014-03-07 27 views
1

的結構我有一個函數fn(),這是reutrning此關鍵字見下文如何檢查的JavaScript

function fn() 
{ 
    return this; 
} 
log(fn() === function, "The context is the global object."); 
//ERROR Unexpected token 

log(fn() === this, "The context is the global object."); 
//true 

我有一個問題FN()===功能爲什麼它是不是真的? fn()和函數是相同的類型 和fn()===這是真的?而FN(),是這同一類型

的不如果我這樣做

function fn(){ 
    //return this; 
} 

然後結果爲假。它意味着fn()===這個條件是將它與fn()的返回值進行比較。

+0

'this'是全局對象(實現爲windows)。因此,比較'這個==這個'無論如何結果'true' –

回答

1

你可能要檢查typeof

function fn() { 
    return this; 
} 
console.log((typeof (fn) == "function"), "The context is the global object."); 
// true, "The context is the global object." 

console.log(fn() === this, "The context is the global object."); 
// true "The context is the global object." 

所以,

  1. fn() === "function" --> false。因爲fn()返回window object並且您將它與字符串"function"進行比較。
  2. fn() === this --- > true因爲this(函數的所有者,即window)和全局對象this (window)是相等的。
+0

@ user13500 yup'typeof'返回字符串 –

+0

@ user13500感謝您指出這一點..blindly發佈 –

+0

@ Pilot- *這*不是[上下文](http: //ecma-international.org/ecma-262/5.1/#sec-10),這是[關鍵字](http://ecma-international.org/ecma-262/5.1/#sec-11.1.1)。如果未由調用設置,則函數的* this *關鍵字默認爲全局對象。如果沒有在嚴格模式下設置,它將被* undefined *。 – RobG

1

如果你想確定類型,嘗試typeof運算符

console.log(typeof(fn) === 'function' ? 'Its a function' : 'Its NOT a function'); 

從我的理解中,「這個」你是從FN返回()是一個窗口對象,不是功能。

1
function fn() 
{ 
    return this; 
} 

console.log((fn() === function)); 
// the output of function is trying to be compared with the function 
// declaration... you can't do that... you need to compare against a value 

console.log((typeof fn === 'function')); 
// the type of fn itself, not its return value, is the string 'function', 
// therefore it is true 

console.log((fn() === this)); 
//the return value of the function is this... this is the window object and 
// this exists, therefore this is true