常见创建对象的几种方式

201 阅读1分钟

1.简单对象的创建

简单对象的创建    使用对象字面量的方式{}   创建一个对象

var tso  = {};//JSON
 tso.name="小王";//添加属性并赋值
 tso.age=19;
 tso.sayHello=function(){
  alert("hello "+tso.name+",今年"+tso["age"]+"岁了");//可以使用“.”的方式访问属性,也可以使用HashMap的方式访问
 }
 tso.sayHello();//调用对象的(方法)函数
 


2.构造函数创建

构造函数的可拓展实例

function Pet(name,age,hobby){
   this.name=name;//this作用域:当前对象
   this.age=age;
   this.hobby=hobby;
   this.eat=function(){
        alert("我叫"+this.name+",我喜欢"+this.hobby+",我已经"+this.age+'岁了。');
   }
}
var maidou =new Pet("麦兜",5,"睡觉");//实例化/创建对象
 
 maidou.eat();//调用eat方法(函数)
 

3.工厂模式创建

解决创建相似对象问题

   //1、原料
    var obj=new Object();
   //2、加工
    obj.name=name;
    obj.showName=function(){
       alert(this.name);
    }     
    //3、出场
     return obj; 
} 
var p1=createPerson('小米');
p1.showName();

4.原型对象创建

实例可以共享属性和方法

    function Dog(){
    }
    Dog.prototype.name="旺财";
    Dog.prototype.eat=function(){
    alert(this.name+"是个吃货");
    }
    var wangcai =new Dog();
    wangcai.eat();

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

省内存并且广义上共享互相的方法并且独有自己的副本

  this.name=name;
  this.price=price; 
}
 Car.prototype.sell=function(){
   alert("我是"+this.name+",我现在卖"+this.price+"万元");
  }
 
var camry =new Car("凯美瑞",27);
camry.sell();