2011-01-22 42 views
2

我對作爲類的函數中的return語句感到困惑。請參閱下面的示例代碼:函數返回語句作爲類

<html> 
<body> 

<script type="text/javascript"> 
function test() { 
    this.abc = 'def'; 
    return 3; 
} 

var mytest = new test(); 

document.write(mytest + ', ' + (typeof mytest) + ', ' + mytest.abc); 

</script> 

</body> 
</html> 

代碼輸出:[object object],object,def。

這是我的問題。我在test()函數中寫了'return 3'。當'new test()'被調用時,這個語句是否被忽略?

感謝。

+0

JavaScript沒有類。 js中的對象基於原型... – Ivan 2011-01-22 19:34:47

回答

3

當你用new調用一個函數時,你會調用它作爲一個構造函數,它會自動返回它構造的新對象。

您的return 3;語句被忽略。什麼是有效的返回是:

{ abc:'def' } 

...有一個隱含的參照prototype對象,這在你的例子不具有任何枚舉的屬性,因爲你沒有給它任何。

如果你做的事:

mytest instanceof test; 

...這將評估爲true

如果你做的事:

function test() { 
    this.abc = 'def'; 
} 
test.prototype.ghi = 'jkl'; 

var mytest = new test(); 

...你可以再做:

mytest.ghi; 

...這將使你的價值'jkl'

3

您可以結帳following article

+0

感謝Darin,我正在尋找! – Shanimal 2014-03-25 15:40:07

+0

萬一文章接着陳舊,我寫了[答案](http://stackoverflow.com/questions/4770070/return-statement-in-a-function-as-class#42603663)與快速摘要 – aljgom 2017-03-05 02:48:10

0

new運算符實例化並返回對象。下面是一些例子,其輸出:

(...) 
var mytest = test(); 
document.write(mytest + ', ' + (typeof mytest) + ', ' + mytest.abc); 
// 3, number, undefined 

或者:

function test() { 
    this.abc = 'def'; 
    this.getvalue = function(){ 
     return 3; 
    } 
} 
var mytest = new test(); 
document.write(mytest.getvalue() + ', ' + (typeof mytest) + ', ' + mytest.abc); 
// 3, object, def 
0

當您使用new運營商,您使用的功能構造,在這種情況下返回值:

  • 如果它不是對象,它(在你的例子一樣)忽略
  • 如果是一個對象,返回的對象成爲整個new表達

的結果,所以,如果你寫

Test = function(arg) { 
    this.a = 1; 
    return arg; 
} 

var t1 = new Test(10); 
var t2 = new Test({b: 2}); 
console.log(t1, t2) 
// output: 
// Test {a:1} Object {b: 2}