默認(rèn)情況下屋剑,函數(shù)的返回值為undefined(即沒有定義返回值)迄薄。
但是構(gòu)造函數(shù)比較例外沽瘦,new構(gòu)造函數(shù)在沒有return的情況下默認(rèn)返回新創(chuàng)建的對象然痊。然而至朗,在有return的情況下,如果返回值為基本數(shù)據(jù)類型(string剧浸,number锹引,boolean,undefined唆香,null)粤蝎,那么返回值仍然為新建對象實例。
只有當(dāng)定義返回一個非基本數(shù)據(jù)類型的對象袋马,函數(shù)的返回值才為指定的對象。在這種情況下秸应,this值所引用的對象就被丟棄了虑凛。
如果指定的返回值是基本數(shù)據(jù)類型的話,仍然會返回新對象
<script>
function A(){
this.x=3;
return "OK";
}
var a = new A();
console.log(a instanceof A); //true
console.log("x" in a); //true
</script>
如果指定返回對象了的話软啼,被返回的對象就成了指定的對象值桑谍。在這種情況下,this值所引用的對象就被丟棄了祸挪。
<script>
function B(){
this.x=3;
return Object("OK");
}
var b = new B();
console.log("x" in b); //false
console.log(b instanceof B); //false
console.log(b instanceof String); //true
</script>
更直觀的例子:
<script>
function User( name, age){
this.name = name;
this.age = age;
// return; // 返回 this
// return null; // 返回 this
// return this; // 返回 this
// return false; // 返回 this
// return 'hello world'; // 返回 this
// return 2; // 返回 this
// return []; // 返回 新建的 []
// return function(){}; // 返回 新建的 function锣披,拋棄 this
// return new Boolean( false); // 返回 新建的 boolean,拋棄 this
// return new String( 'hello world'); // 返回 新建的 string贿条,拋棄 this
// return new Number( 32); // 返回新的 number雹仿,拋棄 this
}
var user=new User("小白",20)
console.log(user);
</script>
返回值為簡單的基本數(shù)據(jù)類型,而不是一個對象(包括基本類型的對象)的話整以,那么返回值仍然為新創(chuàng)建的對象胧辽。
內(nèi)容參考:http://blog.sina.com.cn/s/blog_7a8c8ac90101hzrq.html