首页 > 代码库 > (1) constructor(构造器)

(1) constructor(构造器)

 var Car = function (model, year, miles) {        this.model = model;        this.year = year;        this.miles = miles;        this.carSituation = function () {            console.log(this.model + this.year + this.miles);        };    };    var car1 = new Car(‘bens‘, 2014, 1000);    var car2 = new Car(‘mini‘, 2014, 1000);    car1.carSituation();    car2.carSituation();

  (1)这是一个基本的构造器,内部使用this指针引用新创建的对象,缺点是使继承变得困难。

 

var Car = function (model, year, miles) {        this.model = model;        this.year = year;        this.miles = miles;    };    Car.prototype.carSituation = function(){        console.log(this.model + this.year + this.miles);    };    var car1 = new Car(‘bens‘, 2014, 1000);    var car2 = new Car(‘mini‘, 2014, 1000);    car1.carSituation();    car2.carSituation();

(2)这是一个带原型的构造器,可以创建多个对象,并访问相同的原型,因此可以扩展原始示例

(1) constructor(构造器)