|
<script type="text/javascript">
var lev = function(){
return "啊打";
}
//0工厂方式
function Parent(){
var Child = new Object();
Child.name = "李小龙";
Child.age = "不详";
Child.lev = lev;
return Child;
}
var x = Parent();
//1构造函数方式
function Parent1(){
this.name = "lixiaolong";
this.age = "buxiang";
this.lev = lev;
}
var x1 = new Parent();
//2原型方式
function Parent2(){}
Parent2.prototype.name = "lixiaolong";
Parent2.prototype.age = "buxiang";
Parent2.prototype.lev = lev();//代表lev属性为string 或者Parent2.prototype.lev=lev;--lev为function
var x2 = new Parent2();
//3混合构造函数、原型方式(推荐)
function Parent3(){
this.name = "lixiaolong";
this.age = "buxiang";
}
Parent3.prototype.lev = function(){return this.name;}
var x3 = new Parent3();
//4动态原型模式--保证创建该对象的实例时,属性的方法不会被重复创建
function Parent4(){
this.name = "lixiaolong";
this.age = "buxiang";
if(typeof Parent4._lev=="undefined"){
Parent4.prototype.lev = function(){return this.name}
Parent4._lev = true;
}
}
var x4 = new Parent4();
</script>
<input value="method" type="button" onclick="javascript:alert(typeof(x.lev));alert(x.lev())">
<input value="property" type="button" onclick="javascript:alert(x.name)">
<br/>
<hr>
<input value="method" type="button" onclick="alert(typeof(x1.lev));alert(x1.lev())">
<input value="property" type="button" onclick="alert(x1.name)">
<br/>
<hr>
<input value="method" type="button" onclick="alert(typeof(x2.prototype));alert(typeof(x2.lev));alert(x2.lev())">
<input value="property" type="button" onclick="alert(x2.name)">
<br/>
<hr>
<input value="method" type="button" onclick="alert(typeof(x3.lev));alert(x3.lev())">
<input value="property" type="button" onclick="alert(x3.name)">
<br/>
<hr>
<input value="method" type="button" onclick="alert(typeof(x4.lev));alert(x4.lev())">
<input value="property" type="button" onclick="alert(x4.name)">
<br/>
<hr> |
|