javascript中创建对象的几种方式?

1. 使用Object构造函数来创建一个对象,下面代码创建了一个person对象,并用两种方式打印出了Name的值。

  var person = new Object();

  person.name="kevin";

  person.age=31;

  alert(person.name);

  alert(person["name"])

2. 使用对象字面量的方式{} 创建一个对象(最简单,好理解,推荐使用)

  var Cat = {};//JSON

  Cat.name="kity";//添加属性并赋值

  Cat.age=2;

  Cat.sayHello=function(){

    alert("hello "+Cat.name+",今年"+Cat["age"]+"岁了");//可以使用“.”的方式访问属性,也可以使用HashMap的方式访问

  }

  Cat.sayHello();//调用对象的(方法)函数

3. 用function(函数)来模拟class (无参构造函数)

3.1 创建一个对象,相当于new一个类的实例

    function Person(){

    }

    var personOne=new Person();//定义一个function,如果有new关键字去"实例化",那么该function可以看作是一个类

    personOne.name="dylan";

    personOne.hobby="coding";

    personOne.work=function(){

      alert(personOne.name+" is coding now...");

    }

    personOne.work();

3.2 可以使用有参构造函数来实现,这样定义更方便,扩展性更强(推荐使用)

    function Pet(name,age,hobby){

      this.name=name;//this作用域:当前对象

      this.age=age;

      this.hobby=hobby;

      this.eat=function(){

        alert("我叫"+this.name+",我喜欢"+this.hobby+",也是个吃货");

      }

    }

    var maidou =new Pet("麦兜",5,"睡觉");//实例化/创建对象

    maidou.eat();//调用eat方法(函数)

4. 使用工厂方式来创建(Object关键字)

  var wcDog =new Object();

  }

  wcDog.work();

5. 使用原型对象的方式 prototype关键字

  function Dog(){

  }

  Dog.prototype.name="旺财";

  Dog.prototype.eat=function(){

    alert(this.name+"是个吃货");

  }

  var wangcai =new Dog();

  wangcai.eat();

6. 混合模式(原型和构造函数)

  function Car(name,price){

    this.name=name;

    this.price=price;

  }

  Car.prototype.sell=function(){

    alert("我是"+this.name+",我现在卖"+this.price+"万元");

  }

  var camry =new Car("凯美瑞",27);

  camry.sell();

7. 动态原型的方式(可以看作是混合模式的一种特例)

  function Car(name,price){

    this.name=name;

    this.price=price;

    if(typeof Car.sell=="undefined"){

      Car.prototype.sell=function(){

        alert("我是"+this.name+",我现在卖"+this.price+"万元");

      }

    Car.sell=true;

    }

  }

  camry.sell();