2011-10-31 69 views
1

我在javascript中使用'this'有一個令人困惑的問題。我有一個方法'get_data',它返回一些對象的成員變量。有時它會將對象本身返回給我...我不知道爲什麼。有人可以解釋這裏發生了什麼嗎?this in javascript

function Feed_Item(data) { 
    this.data = data; 
    this.get_data = function() { 
    return this.data; 
    } 

    this.foo = function() { 
    return this.foo2(); 
    } 
    this.foo2 = function() { 
    //here type of this.data() == Feed_Item!!! It should be of type Data 
    } 
    this.bar = function() { 
    //here type of this.data() == Data, as I'd expect 
    } 
} 
+7

你必須向我們展示調用方法的代碼 - 因爲這個調用依賴於它可能會產生影響。另外,什麼'this.data()'?除'data'參數外,您沒有名爲'data'的函數。數據是一個函數嗎? – ZenMaster

+0

函數的this關鍵字的值完全取決於它的調用方式。閱讀['this'關鍵字的答案,不清楚](http://stackoverflow.com/questions/5429739/this-keyword-not-clear)。 – RobG

+1

你真的需要'this.get_data()'嗎?你不能只調用'this.data'嗎?這看起來像你在Java/C++中會做的一些屬性是私有的。 – puk

回答

1

JavaScript中的'this'取決於您如何調用函數。如果'this'沒有綁定到一個對象,這將是窗口對象。

如果你打電話

item = new Feed_Item() 
item.foo() //foo will be called with correct 'this' 

但是,如果你Feed_Item(some_data),你會添加一些功能,以全局的window對象。

有很多文章解釋這個,例如, http://www.digital-web.com/articles/scope_in_javascript/

0

一個好的博客文章,解釋「這個」可以在這裏找到:http://www.scottlogic.co.uk/2010/05/what-is-this/

本質的this的定義是: 這樣做的價值在在該函數被調用的點來確定,並且是設置爲調用函數的對象

但是,有時很難確切地確定該對象是什麼。這是因爲它取決於函數的調用方式。您甚至可以通過調用函數call方法來動態設置該值。

window.str = "hello"; 
    var fn = function(){ 
     alert(this.str); 
    }; 
    fn(); 

運行在瀏覽器控制檯這個代碼給出hello這是str全球window對象的值,但是如果你運行:

fn.call({ 
     str: 'goodbye' 
    }, []); 

你獲得「再見」,根據上下文有已被更改爲傳入的對象。某些庫例如JQuery,ExtJS,...利用這個特性使其更易於使用。