日期:2014-05-16  浏览次数:20312 次

javascript创建对象的几种方式
1。function 创建
function Pet(the_pet_name, the_form_number){  
    this.age = 0;  
    this.pet_name = the_pet_name;  
    this.form_number = the_form_number;  
} 


2。JSON方式来创建
var o={  
		 a:1,  
		 b:"aa",  
		 c:function(){alert("haiwei o");}  
	}


3。使用对象的prototype属性,用一个空构造函数来设置对象名,然后所有的属性和方法都直接用prototype来赋予
function object1(){};  
object1.prototype.a=4;  
object1.prototype.b=function(){alert("haiwei object1");}; 


4。工厂方式
function createobject(){  
    var o=new Object();  
    o.a=1;  
    o.b="w";  
    o.c=function(){};  
    return o;  
} 


测试
function test(){
	var pet1 = new Pet("barney",0);
	var pet2 = new Pet("betty",1);
	alert(pet1.pet_name+"---"+pet2.pet_name);
	alert(o.a+"---"+o.b);
	o.c();
	alert(object1.prototype.a);
	object1.prototype.b();
}


参考http://lighter.iteye.com/blog/186020