基本用法
@H_404_3@function Car(model,year,miles) {
this.model = model;
this.year = year;
this.miles = miles;
this.output= () {
return this.model + "走了" + this.miles + "公里";
};
}
var tom= new Car("大叔",2009,20000);
var dudu= new Car("Dudu",2010,5000);
console.log(tom.output());
console.log(dudu.output());
问题是output()在每次创建对象的时候都重新定义了,没有共享。
可以用如下方式:
更好的方式,使用原型继承output方法:
@H_404_3@ miles;
}
/*
注意:这里我们使用了Object.prototype.方法名,而不是Object.prototype
主要是用来避免重写定义原型prototype对象
*/
Car.prototype.output= () {
;
};
var tom = var dudu = );
console.log(tom.output());
console.log(dudu.output());
除了使用new,可以作为函数调用、call方式
@H_404_3@// 自定义一个output输出内容
this.output = ;
}
}
方法1:作为函数调用
Car("大叔",20000); 添加到window对象上
console.log(window.output());
方法2:在另外一个对象的作用域内调用
var o = new Object();
Car.call(o,"Dudu",1)">);
console.log(o.output());
该代码的方法1有点特殊,如果不适用new直接调用函数的话,this指向的是全局对象window,我们来验证一下:
@H_404_3@作为函数调用
var tom = Car("大叔",1)">);
console.log(typeof tom); "undefined"
console.log(window.output()); "大叔走了20000公里"
这时候对象tom是undefined,而window.output()会正确输出结果,而如果使用new关键字则没有这个问题。
使用instanceof来强制使用new
@H_404_3@if (!(this instanceof Car)) {
var dudu = Car("Dudu",1)">);
console.log( "大叔走了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一个实例返回。
参考地址