2012-03-13 89 views
0

我m使用JavaScript。聲明一個實例變量「this.variable」將工作,直到我的函數將返回一個對象。返回一個字符串,數字不影響它。在返回一個對象的情況下,實例變量不再工作,併成爲「未定義」。請你能幫助我!在一個函數的範圍(在http://jsfiddle.net/woko/vE4rq/2/最新版本的Firefox &鉻的下測試尋找一個樣品)Javascript:函數 - 返回一個對象將無效this.variable

function Funct() { 
    this.varfunc = "this ist a instance"; 
    return false; 
} 

var f = new Funct(); 
console.log(f.varfunc); 

function FunctReturnobj() { 
    this.varfunc = "this ist a instance + return an object"; 
    return {}; 
} 

var fr = new FunctReturnobj(); 
console.log(fr.varfunc) 

回答

0

thisDOMWindow

this在對象範圍內的對象。

0

new運算符將創建一個新對象並在其上應用函數 - this在函數scope中引用該對象。

但是,如果函數被調用時沒有new,或者包含return語句,它將不會作爲「構造函數」執行。 this將指向執行上下文,通常是window對象。

+0

非常感謝,我的解決方案!用return語句調用函數將不會作爲「構造函數」執行 – user1267459 2012-03-13 21:08:37

0

您以錯誤的方式使用構造函數。構造函數不應該自己返回任何東西。您可以使用prototype財產申報「類」 /對象的方法,也可以將它們設置在構造像你已經做的:

function Constructor(value) { 
    this.variable = value; 
} 

var obj = new Constructor('test'); 
obj.variable; // -> Returns 'test'; 

你可以聲明你的方法同樣的方式反對:

function Constructor(value) { 
    this.variable = value; 

    this.say = function(something) { 
    return "I say: " + something; 
    }; 
} 

或者原型方式:

function Constructor(value) { 
    this.variable = value; 
} 

Constructor.prototype.say = function(something) { 
    return "I say: " + something; 
}; 

當然,這一個通用的,有點壞榜樣,但你可能明白了吧:)

+0

感謝您的時間和示例! – user1267459 2012-03-14 19:05:10