码迷,mamicode.com
首页 > Web开发 > 详细

Js创建对象实践

时间:2014-08-28 16:10:10      阅读:258      评论:0      收藏:0      [点我收藏+]

标签:style   http   color   java   io   strong   ar   div   cti   

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创建对象实践

标签:style   http   color   java   io   strong   ar   div   cti   

原文地址:http://blog.csdn.net/qivan/article/details/38898435

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!