构造函数强制使用new

来源:互联网 发布:淘宝卖家退款多久到账 编辑:程序博客网 时间:2024/06/13 21:19
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
原创粉丝点击