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);
?

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。