標籤:js 建立對象
原廠模式
var lev =function(){
return "hello world";
};
function Parent(){
var child=new Object();
child.name="孫悟空";
child.age=400;
child.lev=lev;
return child;
}
var x = Parent();
alert(x.name); alert(x.lev());
建構函式方式
var lev=function(){
return "hello,world";
};
function Parent(){
this.name="孫悟空";
this.age=400;
this.lev=lev;
}
var x=new Parent();
alter(x.name);alert(x.lev());
原型模式
var lev=function(){
return "hello world";
};
function Parent(){};
Parent.Prototype.name="孫悟空";
Parent.prototype.age=400;
Parent.prototype.lev=lev;
var x=new Parent();
alert(x.lev());
混合建構函式
function Parent(){
this.name="孫悟空";
this.age=400;
}
Parent.prototype.lev=function(){
return this.name;
}
var x =new Parent();
alert(x.lev());
動態原型方式
function Parent(){
this.name="孫悟空";
this.age=400;
};
if (typeof Parent._lev=="undefined"){
Parent.prototype.lev=function(){
return this.name;
}
Parent._lev=true;
}
var x=new Parent();
alert(x.lev());
json方式建立
var Parent={
name:"孫悟空",
age:400,
lev:function(){
return "hello world";
}
};
alert(Parent.lev());
js建立對象的方式