构造函数new执行与直接执行的区别

//创建一个Test构造
function Test(){
   // new执行与直接执行 this的不同指向
   this.init();
};
// this 指向 Test
Test.prototype.init = function(){
  console.log('this is Test');
}
// this 指向 window
function init(){
  console.log('this is window');
}

//直接执行
var t = Test(); // this is window
var test = new Test(); //this is Test

 

另补充一点:
构造函数返回值的问题
如果一个函数的返回值是引用类型(数组,对象或者函数)的数据,那么这个函数作为构造函数用new运算符执行构造时,运算的结果将被它的返回值取代,这时候,构造函数体内的this值丢失了,取而代之的是被返回的对象;

//创建一个Test构造
function Test(){
   this.a = 10;
   return {}; 
};

console.log( new Test() ); // Object {}


//创建一个Test构造
function Test(){
   this.a = 10;
   return 1; 
};

console.log( new Test() ); // Test {a: 10}

 参考网站:http://www.jb51.net/article/47871.htm

posted @ 2016-07-01 20:20  marunzhou  阅读(297)  评论(0编辑  收藏  举报