关于构造函数的返回值

很长一段时间认为, 构造函数显式的返回值是无效的, 最终都会返回this。 今天才发现其实是错误的。

当构造函数中没有return语句时, 会默认返回this, 但是也可以返回任意的对象, 如果返回值不是对象, 仍然返回this。 不过这样也有后遗症, 实例将不会继承构造函数原型上的任何属性。

例1:

 function Test() {
     this.name = "this's name";
     var that = {};
     that.name = "that's name";
     return 10;
 }

 var test1 = new Test();
 console.log(test1.name);   // this's name

例2:

 function Test() {
     this.name = "this's name";
     var that = {};
     that.name = "that's name";
     return that;
 }

 var test1 = new Test();
 console.log(test1.name);   // that's name

例3:

 function Test() {
     this.name = "this's name";
     var that = {};
     that.name = "that's name";
     return that;
 }

 Test.prototype.say = function() {
     alert("hi");
 }

 var test1 = new Test();
 console.log(test1.name);   // that's name
 test1.say();         // error
posted @ 2013-08-26 14:59  木头小木头  阅读(457)  评论(0编辑  收藏  举报