2010-11-19 123 views
3

什麼是(內部函數內)引用在下面的代碼上下文中?它是否指向TimeSpan?「this」是指什麼

var TimeSpan = function (days, hours, minutes, seconds, milliseconds) { 
var attrs = "days hours minutes seconds milliseconds".split(/\s+/); 

var gFn = function (attr) { 
    return function() { 
     return this[attr]; 
    }; 
}; 

var sFn = function (attr) { 
    return function (val) { 
     this[attr] = val; 
     return this; 
    }; 
}; 
} 

感謝

+2

在這個例子中'this'沒有提及任何東西,因爲這些函數都沒有被執行。這個取決於函數的調用方式。 – deceze 2010-11-19 07:47:17

回答

10

this值設置隱含取決於的函數是如何調用,有三種情況,其中發生這種情況:

  1. 當無基座對象,或一個非參考參考被調用:

    myFn();    // the myFn reference has no base object 
    (function() {})(); // non-reference 
    

    this值將指向全局對象

  2. 當引用包含基礎對象,例如:

    myObj.method(); 
    

    method內的this值將指向myObj

  3. 當使用new操作者:

    var obj = new Foo(); 
    

    Foo函數內的this值,將指向一個新創建的對象,從Foo.prototype繼承。

this值也可以設置明確,通過使用callapply方法,例如,與call

function test(a) { 
    return alert(this + a); 
} 

test.call("hello", " world"); // alerts "hello world" 

或用apply如果我們需要 「申請」 一個從數組到參數的參數集:

function test(a, b) { 
    return alert(this + a + b); 
} 

var args = ["my ", "world "]; 
test.apply("hello ", args); // alerts "hello my world" 

[1]這改變了在新ECMAScript 5th Strict Mode,現在當與沒有基礎對象,或一個非參考函數引用被調用(作爲第一情況),this值將包含undefined

這是因爲使用構造函數時,人們經常在調用構造函數時忘記使用new運算符。

發生這種情況時,this值指向全局對象,並最終添加了不需要的全局屬性。

現在嚴格的模式,this將包含不確定,如果財產查找,就可以了(this.foo = 'foo')由我們會有的,而不是具有全局foo屬性不錯TypeError例外。

+0

優秀的解釋,不能說更好或更清楚:) – ChrisR 2010-11-19 07:48:59

+0

好說明:) – XMen 2010-11-19 07:54:23

+0

你當然知道你的東西! – 2010-11-19 08:05:02

1

this指當前對象,在這種情況下,你是裏面的功能。所以

var f = function() { 
    this.key = "someValue"; 
} 

console.log(f.key); // prints "someValue" 

在這種情況下this應在最深範圍水平指向函數,而不是TimeSpan:既然一切都在JavaScript是一個對象,你可以使用關鍵字this修改函數對象的屬性。