SOURCE

/*
构造函数
JavaScript 中的构造函数和其它语言中的构造函数是不同的。 通过 new 关键字方式调用的函数都被认为是构造函数。

在构造函数内部 - 也就是被调用的函数内 - this 指向新创建的对象 Object。 这个新创建的对象的 prototype 被指向到构造函数的 prototype。

如果被调用的函数没有显式的 return 表达式,则隐式的会返回 this 对象 - 也就是新创建的对象。
*/


//显式的 return 表达式将会影响返回结果,但仅限于返回的是一个对象。如果是数字等基础类型,不影响返回对象。
function Bar() {
    return 2;
}
console.log(new Bar()); // 返回新创建的对象,不会运行Bar方法
console.log(Bar());

function Test() {
    this.value = 2;

    return {
        foo: 1
    };
}
//console.log(new Test().value); // 返回的对象,所以这里会覆盖新生成的对象。
//console.log(this.value);//new后,调用函数就是不全局对象了。这里首先new生成新对象,然后有覆盖掉了。
console.log(Test().foo);//Test返回对象的值
console.log(this.value)//执行Test后,绑定全局对象。
var t = new Test();
console.log(t.value);
console.log(t.foo);//return 覆盖了new生成对象。
/*


new Bar() 返回的是新创建的对象,而不是数字的字面值 2。 因此 new Bar().constructor === Bar,但是如果返回的是数字对象,结果就不同了,如下所示

function Bar() {
    return new Number(2);
}
new Bar().constructor === Number
译者注:这里得到的 new Test()是函数返回的对象,而不是通过new关键字新创建的对象,因此:

(new Test()).value === undefined
(new Test()).foo === 1

*/

//如果 new 被遗漏了,则函数不会返回新创建的对象。

function Foo2() {
    this.bla = 1; // 获取设置全局参数
}
Foo2(); //给全局对象绑定了bla

console.log(this.bla); 


function Bar2() {
    var value = 1;
    return {
        method: function() {
            return value;
        }
    }
}
Bar2.prototype = {
    foo: function() {}
};

new Bar2();
Bar2();
/*
上面两种对 Bar 函数的调用返回的值完全相同,一个新创建的拥有 method 属性的对象被返回, 其实这里创建了一个闭包。

还需要注意, new Bar() 并不会改变返回对象的原型(译者注:也就是返回对象的原型不会指向 Bar.prototype)。 因为构造函数的原型会被指向到刚刚创建的新对象,而这里的 Bar 没有把这个新对象返回(译者注:而是返回了一个包含 method 属性的自定义对象)。
*/
console 命令行工具 X clear

                    
>
console