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

js对象的创建
1.工厂创建js对象如下
		function createObject(){
			var object = new Object();
			object.name = "lisi";
			object.password = "123456";
			object.get = function(){
				alert(this.name + ", " + this.password);
			};
			return object;
		}
		
		var object1 = createObject();
		object1.get();
		var object2 = createObject();
		object2.get();

当把get方法定义在外时,那get函数对象为所有对象共享
		function createObject(){
			var object = new Object();
			object.name = "lisi";
			object.password = "123456";
			object.get = get;
			return object;
		}
		function get(){
			alert(this.name + ", " + this.password);
		}		

		var object1 = createObject();
		object1.get();
		var object2 = createObject();
		object2.get();

2.构造函数方式
		function Person(username,password){
			this.username = username;
			this.password = password;
			this.get = function(){
				alert(this.username + ", " + this.password);
			}
		}
		
		var person = new Person("lisi","123456");
		person.get();

3.使用原型方式定义对象,那么生成的所有对象会共享原型中的属性,当一个引用改变了其中的属性也会反应到其他对象中去,但是不能在构造方法中为属性赋初值,如
		function Person(){}
		Person.prototype.username = new Array();
		Person.prototype.password = "123";
		Person.prototype.getInfo = function(){
			alert(this.username + ", " + this.password);
		}
		var person1 = new Person();
		person1.username.push("zhansan");
		person1.username.push("lisi");
		person1.password = "456";
		person1.getInfo();
		
		var person2 = new Person();
		person2.getInfo();

Person对象中的属性username为一个数组,当引用person1改变其值时,引用person2所指的属性username也会发生变化,因为属性username数组是共享的

4.使用原型+构造方法来定义对象,对象之间属性互不干扰,方法共享,如
		function Person(){
			this.username = new Array();
			this.password = "123456";
		}
		Person.prototype.get = function(){
			alert(this.username + ", " + this.password);
		}
		
		var p1 = new Person();
		p1.username.push("zhansan");
		p1.get();
		var p2 = new Person();
		p2.username.push("lisi");
		p2.get();

5.动态原型,在构造函数中通过标志量让所有对象共享一个方法,而每个对象拥有自己的属性,如
		function Person(){
			this.username = "zhansan";
			this.password = "123456";
			if(typeof Person.flag == "undefined"){
				Person.prototype.getInfo = function(){
					alert(this.username + ", " + this.password);
				};
				Person.flag = true;
			}
		}
		var p1 = new Person();
		p1.getInfo();
		var p2 = new Person();
		p2.getInfo();