该代码的方法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一个实例返回。 原始包装函数 JavaScript里有3中原始包装函数:number, string, boolean,有时候两种都用: 复制代码 代码如下: // 使用原始包装函数 var s = new String("my string"); var n = new Number(101); var b = new Boolean(true);
// 推荐这种 var s = "my string"; var n = 101; var b = true;