你的位置:首页 > Java教程

[Java教程]定义js类的几种方法


<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>test</title>

</head>
<body>
<ul>
<li><a >sfsda</a></li>
<li><a >sdfsd</a></li>
<li><a >sdfsd</a></li>
<li><a >sdfsd</a></li>
<li><a >fdsf</a></li>
</ul>
</body>
<script type="text/javascript" >
//工厂方式
function showname(){
alert(this.color)
}
function a(color,name){
var b ={};
b.color=color;
b.name=name;
b.showname=showname;
return b;
}

var c1=a("red","sb");
var c2=a("blue","jb");
c1.showname();
c2.showname();

//构造函数
function w(color,door){
this.color = color;
this.doors = door;
this.showColor = function(){
alert(this.color)
};
}
var w1 = new w("构造",4);
var w2 = new w("构造函数",4);

w1.showColor();
w2.showColor();


//原型方法
function a1(){

}
a1.prototype.color='red';
a1.prototype.doors="4";
a1.prototype.arr=new Array("a","b");
a1.prototype.showColor=function(){
alert(this.color);
}

var a11 = new a1();
var a22 = new a1();
a11.arr.push("c");
alert(a11.arr); //output:aa,bb,cc
alert(a22.arr); //output:aa,bb,cc

//构造函数/原型
function Car(color,door){
this.color = color;
this.doors = door;
this.arr = new Array("aa","bb");
};
Car.prototype.showColor=function(){
alert(this.color);
}
var car1 = new Car("red",4);
var car2 = new Car("blue",4);
car1.arr.push("cc");
console.log(car1.arr); //output:aa,bb,cc
console.log(car2.arr); //output:aa,bb


//动态原型方式
function m(color,door){
this.color = color;
this.doors = door;
this.arr = new Array("ww","ll");
if(typeof m._initialized == "undefined"){
m.prototype.showColor = function(){
alert(this.color);
};
m._initialized = true;
}
}
var m1= new m("gray","23");
var m2= new m("12green","23");
m1.showColor();
m2.showColor();
</script>
</html>