JS 中的 new

来源:互联网 发布:倩女幽魂手游for mac 编辑:程序博客网 时间:2024/04/29 00:56

转自《深入理解JavaScript系列(26):设计模式之构造函数模式》

function Car(model, year, miles) {    this.model = model;    this.year = year;    this.miles = miles;    // 自定义一个output输出内容    this.output = function () {        return this.model + "走了" + this.miles + "公里";    }}//方法1:作为函数调用Car("大叔", 2009, 20000);  //添加到window对象上console.log(window.output());//方法2:在另外一个对象的作用域内调用var o = new Object();Car.call(o, "Dudu", 2010, 5000);console.log(o.output()); console.log(window.o.output());  //等同上面

该代码的方法1有点特殊,如果不适用new直接调用函数的话,this指向的是全局对象window,我们来验证一下:

//作为函数调用var tom = Car("大叔", 2009, 20000);console.log(typeof tom); // "undefined"console.log(window.output()); // "大叔走了20000公里"

这时候对象tom是undefined,而window.output()会正确输出结果,而如果使用new关键字则没有这个问题,验证如下:

//使用new 关键字var tom = new Car("大叔", 2009, 20000);console.log(typeof tom); // "object"console.log(tom.output()); // "大叔走了20000公里"

强制使用new

上述的例子展示了不使用new的问题,那么我们有没有办法让构造函数强制使用new关键字呢,答案是肯定的,上代码:

function Car(model, year, miles) {    if (!(this instanceof Car)) {        return new Car(model, year, miles);    }    this.model = model;    this.year = year;    this.miles = miles;    this.output = function () {        return this.model + "走了" + this.miles + "公里";    }}var tom = new Car("大叔", 2009, 20000);var dudu = Car("Dudu", 2010, 5000);console.log(typeof tom); // "object"console.log(tom.output()); // "大叔走了20000公里"console.log(typeof dudu); // "object"console.log(dudu.output()); // "Dudu走了5000公里"

通过判断this的instanceof是不是Car来决定返回new Car还是继续执行代码,如果使用的是new关键字,则(this instanceof Car)为真,会继续执行下面的参数赋值,如果没有用new,(this instanceof Car)就为假,就会重新new一个实例返回。

0 0
原创粉丝点击