Js new到底发生了什么

在Js中,我们使用了new关键字来进行实例化

那么在这个new的过程中到底发生了什么?

 

关于构造函数的return

正常来讲构造函数中是不用写return语句的,因为它会默认返回新创建的对象。

但是,如果在构造函数中写了return语句,如果return的是一个对象,那么函数就会覆盖掉新创建的对象,而返回此对象。

如果return的是基本类型如字符串、数字、布尔值等,那么函数会忽略掉return语句,还是返回新创建的对象。

1 function Foo(){
2     this.a = 1;
3     this.b = 2;
4 }
5 Foo.prototype.sayMessage = function(){
6     console.log(this.a+ this.b);
7 }
8 
9 var obj = new Foo();

我们来看看返回了什么:

 1 function Foo(){
 2     this.a = 1;
 3     this.b = 2;
 4     return {
 5         myName: 'GaryGuo'
 6     }
 7 }
 8 Foo.prototype.sayMessage = function(){
 9     console.log(this.a+ this.b);
10 }
11 
12 var obj = new Foo();

我们再来看看返回了什么:

 

其实在new的过程中发生了四步操作:

1 var obj = new Object();
2 obj.__proto__ = Foo.prototype;
3 var returnVal = Foo.apply(obj, arguments);
4 obj = (returnVal instanceof Object && returnVal) || obj;

 

posted @ 2017-01-06 16:44  Gary郭伟涵  阅读(852)  评论(0编辑  收藏  举报