Js创建对象的做法

1.对象工具包
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="viewport"
content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no" />
<title>testdiv</title>
<script type="text/javascript" src="./../../Script/jquery.js"></script> </head> <body>
<a href="javascript:void" id="showdiv">sssss</a>
</body>
<script>
var ss = {};
ss.tools = function(){
var a=1;
var b=2;
return{
aaa:a,
show_1:function(){
return a+b;
},
show_2:function(){
return a-b;
}, }
}();
$("#showdiv").click(function(){
var xx = ss.tools.show_1();
alert(xx); var xx2 = ss.tools.show_2();
alert(xx2);
})
</script>
</html>

2.工厂模式

	function createPerson(name,age,job){
var o = {
name:name,
age:age,
job:job,
sayName:function(){
alert(this.name);
}
};
return o;
};
var wyz1 = createPerson("wyz","30","female");
var wyz2 = createPerson("wyz2","30","male");
wyz1.sayName();
wyz2.sayName();




3.构造函数模式 this
	function MathFunc(a,b)
{
this.a = a;
this.b = b;
this.add = function()
{
return a+b;
}
} var add = new MathFunc(3,4);
var sum = add.add();
alert(sum);

4.​Apply和call
	function MathFunc(a,b)
{
this.a = a;
this.b = b;
this.add = function()
{
return a+b;
}
}
var myadd={};
//MathFunc.call(myadd,31,4);
MathFunc.apply(myadd,[31,4]);
var sum = myadd.add();
alert(sum);

5.原型共享方法
	function MathFunc(a,b)
{
this.a = a;
this.b = b;
MathFunc.prototype.add = function()
{
return a+b;
}
};
var myadd= new MathFunc(3,4);
var sum = myadd.add();
alert(sum);

版权声明:本文博客原创文章,博客,未经同意,不得转载。

上一篇:LoadRunner脚本


下一篇:Struts2中ModelDriven的陷阱及其预防