javascript定义对象

一、可以动态添加对象属性,可以动态删除对象属性

<script type="text/javascript">

var object=new Object();
object.username="zhangsan";
alert(object.username);
delete object.username;
alert(object.username);

</script>

二、定义对象最常见的方式

<script type="text/javascript">

var object={username:"zhangsan",password:123};
alert(object.username);
alert(object.password);

</script>

三、工厂方式

<script type="text/javascript">
function createObject(){
var object=new Object();
object.username="zhangsan";
object.password="123";
object.get=function(){
alert(this.username+","+this.password);
}
}
</script>

var obj1=createObject();
var obj2=createObject();

obj1.get();

带参数的构造方法:

function createObject(username,password){
var object=new Object();
object.username=username;
object.password=password;
object.get=function(){
alert(this.username+","+this.password);
}
return object;
}

var object1=createObject("zhangsan","123");
object1.get()

让一个函数对象被多个对象所共享,而不是每一个对象拥有一个函数对象:

function get(){
alert(this.username+","+this.password);
}


function createObject(username,password){
var object=new Object();
object.username=username;
object.password=password;

object.get=get;
return object;
}
var object1 =createObject("zhangsan","123");
var object2 =createObject("lisi","456");
object1.get();
object2.get();

四、构造函数方式:

function person(){

this.username="zhangsan";
this.password="123";

this.getInfo=function(){
alert(this.username+","+this.password);
}
}
var p1=new person();
p1.getInfo();

带参数的构造方法:

function person(username,password){

this.username=username;
this.password=password;

this.getInfo=function(){
alert(this.username+","+this.password);
}
}
var p1=new person("zhangsan",2);
p1.getInfo();

五、原型方式(prototype)

function person(){

}
person.prototype.username=new Array();
person.prototype.password="123";
person.prototype.getInfo=function(){
alert(this.username+","+this.password);
}
var p1=new person();
var p2=new person();
p1.username.push("zhangsan");
p1.username.push("lisi");
p1.password="456";
p1.getInfo();
p2.getInfo();

单纯使用原型方式无法为属性赋初值,只能在对象生成后再去改变值
原型方式会共享属性


六、使用原型+构造函数方式来定义对象(对象之间属性互不干扰,共享同一个方法)

function person(){
this.username=new Array();
this.password="123";
}
person.prototype.getInfo=function(){

alert(this.username+","+this.password);
}
var p1=new person();
var p2=new person();
p1.username.push("zhangsan");
p2.username.push("lisi");
p1.getInfo();
p2.getInfo();

七、动态原型(在构造函数中通过标志量让所有对象共享一个方法,而每个对象拥有自己的属性)

function person(){
this.username="zhangsan";
this.password="123";

if(typeof person.flag=="undefined"){
alert("invoked");
person.prototype.getInfo=function(){
alert(this.username+","+this.password);

}
person.flag=true;
}
}
var p=new person();
var p2=new person();
p.getInfo();
p2.getInfo();

 







 

posted @ 2012-02-17 11:51  一直在等  阅读(751)  评论(0编辑  收藏  举报