首页 > 代码库 > Js创建对象实践

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 tanya = createPerson("tanya","30","female"); 
var ansel = createPerson("ansel","30","male"); 
tanya.sayName(); 
ansel.sayName();
?


3.构造函数模式 
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);
?

Js创建对象实践