js创建对象的方式

来源:互联网 发布:mysql geometry 编辑:程序博客网 时间:2024/05/19 17:59
//创建对象方式一 - 普通方式var car1 = new Object();car1.name = '奔驰';car1.color = 'red';car1.desc = function(){    return this.name + '-' + this.color;}//alert(car1.desc());//创建对象方式二 - 工厂模式function createCar(name, color){    var car = new Object();    car.name = name;    car.color = color;    car.desc = function(){        return this.name + '-' + this.color;    }    return car;}var car2 = createCar('宝马', 'black');var car3 = createCar('大众', 'yellow');//alert(car2.desc());//alert(car3.desc());//创建对象方式三 - 构造方法function Car(name, color){    this.name = name;    this.color = color;    this.desc = function(){        return this.name + '-' + this.color;    }}var car3 = new Car('奥迪', 'blue');//alert(car3.desc());//创建对象方式四 - 原型方法function NewCar(){}NewCar.prototype.name = '长城';NewCar.prototype.color = 'green';NewCar.prototype.desc = function(){    return this.name + '-' + this.color;}var car4 = new NewCar();//alert(car4.desc());//创建对象方式五 - 混合的构造函数和原型方法【用构造函数定义对象的所有非函数属性,用原型定义对象的函数属性】function MyCar(name, color){    this.name = name;    this.color = color;}MyCar.prototype.desc = function(){    return this.name + '-' + this.color;}var car5 = new MyCar('QQ', 'grey');var car6 = new MyCar('奥拓', 'red');//alert(car5.desc());//alert(car6.desc());//创建对象方法六 - 动态原型方法function MyNewCar(name, color){    this.name = name;    this.color = color;    if(typeof MyNewCar._initialized == 'undefined'){        MyNewCar.prototype.desc = function(){            return this.name + '-' + this.color;        };        MyNewCar._initialized = true;    }}var car7 = new MyNewCar('比亚迪', 'blue');//alert(car7.desc());//采用哪种方式 推荐采用方法五或方法六


原创粉丝点击