new 操作的过程如下:
1. 创建一个空对象 {}, 并将 this 指向该空对象;
2. 将 this 的 proto 指向构造函数的 prototype;
3. 执行构造函数, 如果构造函数返回值为对象, 那么就返回该对象; 如果构造函数没有显式返回值或者返回值为基本数据类型, 那么直接忽略这些返回值, 而是返回 this.
- function F(){
- this.x=2;
- return {
- b:7
- };
- }
- var a=new F(); // 结果 a={
- b:7
- }[/code]
- function F(){
- this.x=2;
- return 5;
- }
- var a=new F(); // 结果 a={
- x:2
- }[/code]
- function F(){
- this.x=2;
- return 'sdf';
- }
- var a=new F(); // 结果 a={
- x:2
- },a 的 constructor 为函数 F[/code]
- function F(){
- this.x=2;
- return new String('sdf');
- }
- var a=new F(); // 结果 a 为 String 对象, a 的 constructor 为函数 String[/code]
- function F(){
- this.x=2;
- return function(){
- };
- }
- var a=new F(); // 结果 a 为匿名函数, a 的 constructor 为函数 Function[/code]
来源: http://www.qdfuns.com/article/17631/5e44b73a9489b8c8d0bba5fe6710b32b.html